解决.net5调用DLL用StringBuilder接收时乱码的问题
比如如下调用
[DllImport("CDLLDemo.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] private static extern IntPtr ParseBaliseMsg5([MarshalAs(UnmanagedType.LPStr)]StringBuilder msg, string rmsg, [MarshalAs(UnmanagedType.LPStr)]StringBuilder t);
改成
[DllImport("CDLLDemo.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] private static extern IntPtr ParseBaliseMsg5([MarshalAs(UnmanagedType.LPStr)]StringBuilder msg, string rmsg, ref IntPtr t);
调用
IntPtr sb5= Marshal.StringToHGlobalAnsi("str");
var r5 = ParseBaliseMsg5(sb5E_para, "", ref sb5); var str= Marshal.PtrToStringAnsi(r5);
这样获取出来的str就不再是乱码了