【问题标题】:C# COM string is corrupted in C++ BSTRC# COM 字符串在 C++ BSTR 中损坏
【发布时间】:2013-06-10 05:39:33
【问题描述】:

我编写了一个从我的本地 C++ 代码调用的 C# COM 对象。 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...
}

再次感谢您的帮助!!!!

【问题讨论】:

  • 如果没有实际的代码 sn-ps,想法是不可能的。 BSTRs 不会无缘无故损坏。
  • 请告诉我们您如何调用 C# COM 对象。还有什么让你说字符串已损坏?字符串在内存中的表示形式是什么?
  • @RomanR.,我添加了代码。非常感谢!

标签: c# c++ com


【解决方案1】:

“它适用于 x64”强烈暗示您的调用约定不匹配。 x64 只有一种调用约定,但 x86 有多种。

确保您的事件处理程序被声明为 stdcall。

【讨论】:

  • 它必须是 STDCALL。那里没有检查,编译器会传递错误的函数引用。
  • 你是对的!!!! :-) 我错过了...我不知道 x64 有一个调用约定...! :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 2012-03-29
相关资源
最近更新 更多