简体   繁体   English

如何将字符串参数从c ++ com传递到c#?

[英]How to pass string parameters from c++ com to c#?

I have c++ code that has a parameter like this: 我有具有这样的参数的c ++代码:

STDMETHODIMP TVinaImpl::test(BSTR Param1)
{
  try
  {
      Param1=(L"test1");
  }
  catch(Exception &e)
  {
    return Error(e.Message.c_str(), IID_IVina);
  }
  return S_OK;
}  

I use c++ builder: 我使用C ++ Builder:
在此处输入图片说明
When I call this com dll function in c# it shows me the error: 当我在C#中调用此com dll函数时,它显示了以下错误:

IntPtr a = new IntPtr();
vina.test(a);

it is null and did not get the value. 它为null,未获取值。
How can I pass variable from C# to c++ com and pass back it? 如何将变量从C#传递到c ++ com并传递回去?

Since Param1 is declared as an [in, out] parameter, you need to declare it as a pointer to a BSTR: STDMETHODIMP TVinaImpl::test(BSTR* Param1) 由于Param1被声明为[in, out]参数,因此您需要将其声明为指向BSTR的指针: STDMETHODIMP TVinaImpl::test(BSTR* Param1)

Furthermore, you cannot simply assign a string literal to a BSTR. 此外,您不能简单地将字符串文字分配给BSTR。 The correct way is to allocate memory using SysAllocString : *Param1 = SysAllocString(L"test1"); 正确的方法是使用SysAllocString分配内存: *Param1 = SysAllocString(L"test1");

I'd recommend you declare the argument Param1 as [out, retval] . 我建议您将参数Param1声明为[out, retval] You are not using Param1 as any kind of input. 您没有将Param1用作任何输入。

STDMETHODIMP TVinaImpl::test(BSTR* Param1)
{
  try
  {
      *Param1= SysAllocString(L"test1");
  }
  catch(Exception &e)
  {
    return Error(e.Message.c_str(), IID_IVina);
  }
  return S_OK;
}  

Then when you call the function from C# it is just, 然后,当您从C#调用函数时,

string s = vina.test();

The .Net runtime manages marshalling of data from .Net to COM and vice versa. .Net运行时管理从.Net到COM的数据编组,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM