Converting C++ string/wchar_t* to C# string?

强颜欢笑 提交于 2019-12-01 08:38:54

问题


Question: I need to call a C# dll from a C++ executable. I use COM, and it works fine for int, long and bool. But I can't get a string along...

The IDL file says it's a BSTR, but I can't pass it correctly, and neither retrieve one. I tried using wchar_t* and using sysalloc as I did with VB6, but that doesn't seem to work.

Anybody knows how, or what might be wrong ?


回答1:


If you're using ATL you can do this:

std::string theString = "hello";
CComBSTR bstr(theString.c_str());
DoSomething(bstr);  // Function that takes a BSTR as an argument

Or if no ATL:

const wchar_t* theString = L"hello";
BSTR bstr = SysAllocString(theString);
DoSomething(bstr);
SysFreeString(bstr);


来源:https://stackoverflow.com/questions/2561927/converting-c-string-wchar-t-to-c-sharp-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!