为什么当我使用字符串 return 类型的 OCX 方法时 C# 程序关闭?

why C# program is closed when I used my OCX method with string return type?

我制作了一个 C++ 生成器 ActiveX 库。 当我制作连接到套接字并检查连接并从套接字读取并在套接字上写入的拳头 OCX 时。所有功能都在工作,但功能(从套接字读取并将字符串发送到 ActiveX 容器)return 类型为 BSTR(字符串)无效。 在 运行 将此代码 运行 项目关闭后,程序突然关闭。 如何使用此功能将从套接字读取的数据发送到 ActiveX 容器?

 //============ c++ builder xe8================
//I change the code to just return simple output"123"
//but it can not retun and c# program closed  
BSTR STDMETHODCALLTYPE TSock4Impl::Read()
{
    WCHAR ch[10];
    ch[0]='1';
    ch[1]='2';
    ch[2]='3';
    return ch;
}  
//=============c# code ================
 private void Form1_Load(object sender, EventArgs e)
 {
     //label1.Text = axVinaSock41.Read();
       int a = axSock41.ConStatus();
       label1.Text = Convert.ToString(a);
       label1.Text = axVinaSock41.Read();// in this line the program was closed.
 }  

我的问题解决了。创建 BSTR 并在 COM 对象之间传递它时,必须注意它使用的内存。

BSTR STDMETHODCALLTYPE TSock4Impl::Read()
{
    WCHAR ch[10];
    ch[0]=L'1';
    ch[1]=L'2';
    ch[2]=L'3';
    return ::SysAllocStringLen(ch, 3);
}  

参考:Allocating and Releasing Memory for a BSTR