是否可以将LPWSTR从C ++ DLL返回到C#应用程序

问题描述:

C ++函数定义是

__declspec(dllexport) LPWSTR __stdcall GetErrorString(int errCode);

我在C#中这样称呼它

 [DllImport("DLLTest.dll")]
 public static extern string GetErrorString(int errCode);

 static void Main(string[] args)
{
    string result = GetErrorString(5);
}

我收到了System.Runtime.InteropServices.SEHException类型的未处理异常

I get an unhandled exception of type System.Runtime.InteropServices.SEHException

我什至不确定C ++ DLL是否可以尝试将LPWSTR返回到C#...

I'm not even sure if it's ok for the C++ DLL to try to return a LPWSTR to C#...

谢谢。

您可能想尝试以下方法:

You might want to try something like this:

[DllImport("DLLTest.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string GetErrorString(int errCode);