C#通过引用C ++ ActiveX控件传递int和字符串:类型不匹配

时间:2009-12-01 11:23:40

标签: c# c++ activex pass-by-reference

我有一个问题,通过引用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#中的字符串类型和C ++ ActiveX中的LPCTSTR *会发生同样的异常。 任何提示或建议将不胜感激。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这只是一个很长的镜头(没有双关语),但请尝试使用“long”数据类型为.net resultCode变量。