C# COM 字符串在 C++ BSTR 中损坏

标签 c# c++ com

我写了一个 C# COM 对象,我从我的 native C++ 代码中调用它。 C# COM 有一些函数和事件。

我在 C++ 中注册了事件,并调用了 C# 对象。 在某个时刻调用事件,将 C# 字符串作为参数发送到已损坏的 C++ BSTR。

我尝试了所有我能想到的,然后到处查看:-(

有谁知道为什么 BSTR 被破坏了???

编辑: 重要信息:

  1. 它适用于 x64 位,错误仅发生在 x86 版本上。
  2. 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/

相关文章:

c++ - 如何使 C++ 实时服务器应用程序保持现代 Web 客户端界面?

c# - 使用 jquery 将客户端事件绑定(bind)到动态数据列表项

c# - 如何为必须相等且可以选择用空格分隔的任意数字字符串创建正则表达式

c++ - vector 的初始化 vector

delphi - 在 Delphi 中重命名 DLL

c++ - 数字 ErrorMessage 的含义

c# - 找到与请求 (GET) 匹配的多个操作

c# - Xamarin-Studio Android 窗体设计器 : Android Version not installed

c++ - 使用 Windows 消息和 directx 9 处理键盘输入

c++ - 字符串分配的段错误