Dav*_*nan 47
我这样做是BSTR因为它意味着你不必每个字符串调用两次,一次获取长度然后一次获取内容.
使用BSTRmarshaller将负责BSTR使用正确的内存管理器解除分配,以便您可以安全地将其从C++代码中传出.
C++
#include <comutil.h>
BSTR GetSomeText()
{
return ::SysAllocString(L"Greetings from the native world!");
}
Run Code Online (Sandbox Code Playgroud)
C#
[DllImport(@"test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string GetSomeText();
Run Code Online (Sandbox Code Playgroud)
有一个小缺点BSTR,即它带有UTF-16有效载荷,但你的源数据可能很好char*.
要解决这个问题,您可以将转换结束char*为BSTR:
BSTR ANSItoBSTR(const char* input)
{
BSTR result = NULL;
int lenA = lstrlenA(input);
int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
if (lenW > 0)
{
result = ::SysAllocStringLen(0, lenW);
::MultiByteToWideChar(CP_ACP, 0, input, lenA, result, lenW);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这是方式的最难的了,现在可以很容易地添加其他包装转换到BSTR从LPWSTR,std::string,std::wstring等.
这是一个讨论过字符串封送处理的主题。
需要用属性标记参数
[MarshalAs(UnmanagedType.LPSTR)]
Run Code Online (Sandbox Code Playgroud)