【问题标题】:Marshalling C# types to call a C++ IDispatch interface results in a type mismatch编组 C# 类型以调用 C++ IDispatch 接口会导致类型不匹配
【发布时间】:2012-01-30 15:24:14
【问题描述】:

我正在尝试使用以下方法定义调用 c++ IDispatch 接口:

ATL HRESULT TestFunc(long Command, [in, out] long* pData, [in, out] BSTR* pString, [out, retval] long* pRC);

// ...
Type t = Type.GetTypeFromProgID( "IMyTestInterfce" );
Object so = Activator.CreateInstance(t);
Object[] args = new Object[3];               
args[0] = -8017;
args[1] = 0;
args[2] = "";
Object result = so.GetType().InvokeMember("TestFunc", BindingFlags.InvokeMethod, null, so, args);

调用的结果是类型不匹配,但我不知道为什么。

InnerException = {"类型不匹配。(来自 HRESULT 的异常:0x80020005 (DISP_E_TYPEMISMATCH))"}`

谢谢

【问题讨论】:

  • @Ramhound 我通常会,但在这种情况下,我需要使用后期绑定。

标签: c# c++ com


【解决方案1】:

您的问题是第二个和第三个参数(pDatapString)在其定义中标记为 [in, out],这意味着它们在 C# 中转换为 ref 参数。您需要使用接受ParameterModifier[] 参数的the overload of InvokeMember 来指定这些参数应该通过引用而不是值传递。 ParameterModifier 的数组应包含一个元素,该元素将第二个和第三个索引指定为true,以表明它们是通过引用传递的。

ParameterModifier modifier = new ParameterModifier(3);
modifier[1] = true;
modifier[2] = true;

Object result = so.GetType().InvokeMember(
    "TestFunc",                           // name
    BindingFlags.InvokeMethod,            // invokeAttr
    null,                                 // binder
    so,                                   // target
    args,                                 // args
    new ParameterModifier[] { modifier }, // modifiers
    null,                                 // culture
    null                                  // namedParameters
);

【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2017-08-03
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多