C#通int和串通过参考C ++ ActiveX控件:类型不匹配(C# pass int and s

2019-10-18 12:38发布

我具有由参考int或字符串变量传递到C ++ ActiveX控件的问题。 我也参照C ++ DLL通过这些变量,一切工作正常。

C ++ DLL:

__declspec (dllexport) void
Execute (LPCTSTR cmd, int& resultCode, LPCTSTR& message, long& receiptNumber)
{
    message = _T("ReplyProblem");
    resultCode = 100;
    receiptNumber = -1;
}

C#:

[DllImport("MyCOM.dll", CharSet = CharSet.Unicode)]
public static extern void Execute (string cmd, out int resultCode, out string message, out int receiptNumber);
...
int resultCode = 0;
string message = "";
int receiptNumber = 0;
Execute ("cmd", out resultCode, out message, out receiptNumber); // OK

如何得到这个ActiveX控件做了什么? 我试着用&符号来定义的方法,但MIDL编译器并没有允许。

MyCOM.idl:

[id(1025315)] void Execute (LPCTSTR cmd, [out]long& returnCode); // MIDL2025: syntax error

我修改了的方法来使用指针*。

MyCOM.idl:

[id(1025315)] void Execute (LPCTSTR cmd, [out]long* returnCode);

MyCOMCtrl.h:

// Dispatch maps
afx_msg void Execute (LPCTSTR cmd, long* resultCode);

MyCOMCtrl.cpp

// Dispatch map
...
DISP_FUNCTION_ID(MyCOMCtrl, "Execute", DISPID_EXECUTE_METHOD, Execute, VT_EMPTY, VTS_PI4)
...

void MyCOMCtrl::Execute (LPCTSTR cmd, long* resultCode)
{
    *resultCode = 111;
}

C#:

using MyCOMLib;
...
MyCOM client = new MyCOM();
int resultCode = 0;

// COMException: Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
client.Execute ("Test command", out resultCode);

发生相同的异常使用C#字符串类型和LPCTSTR *在C ++中的ActiveX代替。 任何提示或建议,将不胜感激。

Answer 1:

解决了:

在MyCOMCtrl.cpp:

// Dispatch map
...
DISP_FUNCTION_ID(MyCOMCtrl, "Execute", DISPID_EXECUTE_METHOD, Execute, VT_EMPTY, VTS_PI4)
...

一定是:

DISP_FUNCTION_ID(MyCOMCtrl, "Execute", DISPID_EXECUTE_METHOD, Execute, VT_EMPTY, VTS_BSTR VTS_PI4) // two VTS arguments


Answer 2:

这仅仅是一个长镜头(没有双关语意),但尝试使用“长”的数据类型为你的.NET resultCode为变量。



文章来源: C# pass int and string by reference to C++ ActiveX Control: type mismatch