是否可以将LPWSTR从C ++ DLL返回到C#app

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类型的未处理exception

我甚至不确定C ++ DLL是否可以尝试将LPWSTR返回给C#…

谢谢。

您可能想尝试这样的事情:

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

请参阅此处接受的答案: PInvoke for C函数返回char *

简短版本:您必须将返回值编组为IntPtr或.NET运行时做出一些假设并尝试删除char指针指向的内存。 如果运行时所做的假设是错误的,这可能会导致崩溃。