[英]Decimal marshaling in COM-Interop
I have COM object method with signature 我有带签名的COM对象方法
HRESULT _stdcall Method1([in] int ms);
Next, i call this method from C# by reflection: 接下来,我通过反射从C#调用此方法:
... decimal ms = 100.5m; comType.InvokeMember("Method1", flags, null, comObject, new object[] { ms }); ...
Is this call correct ? 这个电话正确吗? I mean how decimal ms will be marshaled to int ?
我的意思是十进制 ms将如何封送为int ?
This code works if i create instance by Activator 如果我通过Activator创建实例,则此代码有效
var comType= Type.GetTypeFromProgID("MyCom.Server", false); var comObject= Activator.CreateInstance(comType);
Thanks! 谢谢!
The first snippet makes an early-bound call, using the Runtime Callable Wrapper that was created when you added a reference to the COM server. 第一个片段使用在向COM服务器添加引用时创建的运行时可调用包装程序进行早期绑定调用。 It is not going to enjoy you passing a decimal when the argument type is int, Reflection won't convert argument values for you.
当参数类型为int时,您不会喜欢传递小数点,Reflection不会为您转换参数值。
The second snippet makes a late-bound call, using IDispatch::Invoke(). 第二个片段使用IDispatch :: Invoke()进行后期绑定调用。 The decimal is converted to a VARIANT of type VT_DEC.
小数转换为VT_DEC类型的VARIANT。 The IDispatch implementation in the COM server then converts that variant to the required argument type.
然后,COM服务器中的IDispatch实现将该变量转换为所需的参数类型。 The COM automation helper function VarI4FromDec() probably does that, depends if the server implemented IDispatch itself or left it up to the stock implementation.
COM自动化帮助程序函数VarI4FromDec()可能会这样做,具体取决于服务器是自己实现IDispatch还是将其留给库存实现。
Since you are already using an RCW, neither code snippet makes much sense. 由于您已经在使用RCW,所以这两个代码段都没有多大意义。 Just use comObject.Method1(ms).
只需使用comObject.Method1(ms)。 The C# compiler will coerce the decimal for you.
C#编译器将为您强制转换十进制。 If you favor using late binding, slow but safe, you really want to favor the dynamic keyword in C# version 4 and up.
如果您喜欢使用缓慢但安全的后期绑定,那么您真的想在C#版本4和更高版本中使用dynamic关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.