我写了一个 C# COM 对象,我从我的 native C++ 代码中调用它。 C# COM 有一些函数和事件。
我在 C++ 中注册了事件,并调用了 C# 对象。 在某个时刻调用事件,将 C# 字符串作为参数发送到已损坏的 C++ BSTR。
我尝试了所有我能想到的,然后到处查看:-(
有谁知道为什么 BSTR 被破坏了???
编辑: 重要信息:
- 它适用于 x64 位,错误仅发生在 x86 版本上。
- C# COM 被编译为任何 CPU。我尝试将其编译为 x86,但没有任何区别。
CS代码,调用事件:
// declaring the event and delegate
public delegate void on_start_delegate(string dict_param);
public event on_start_delegate on_start_click;
void on_start(mydictionary dictparams)
{
string strparams = dictparams.ToString();
Trace.WriteLine(strparams); // the string is fine
if (on_start_click != null)
on_start_click(strparams); // <--- Calling C++
}
连接点类:
[Guid("0581E......")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface Iregistration_form_events
{
[DispId(1)]
void on_start_click(string dict_param);
}
在C++中,注册事件:
BEGIN_SINK_MAP(registraion_form)
SINK_ENTRY_INFO(SENSOR_REG_SINK_ID, __uuidof(namespace::Iregistration_form_events), 1, on_start_click, &on_start_click_info)
END_SINK_MAP()
_ATL_FUNC_INFO registraion_form::on_start_click_info = {CC_STDCALL, VT_EMPTY, 1, {VT_BSTR}};
BSTR被破坏的函数:
void registration_form::on_start_click( BSTR params ) // <-- params get corrupted!
{
dictionary dictparams;
std::wstringstream ss;
ss << params;
ss >> dictparams;
// do more stuff...
}
再次感谢您的帮助!!!!
最佳答案
“It works on x64”强烈暗示您的调用约定不匹配。 x64 只有一种调用约定,而 x86 有多种调用约定。
确保您的事件处理程序被声明为 stdcall。
关于C# COM 字符串在 C++ BSTR 中损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17093797/