為了這個問題,百度了一堆不靠譜的資料,什么C#調用c++類型對應啥的,說用string ,StringBuilder,Byte[]等,試了全部不行。其實是個很簡單的問題,這里做個記錄吧:
C++端:(定義返回數據為結構體Vector4)
struct Vector4 { float A, B, C; const char* D; };
C#端:(接收返回的結構體Vector4)
[StructLayout(LayoutKind.Sequential)] struct Vector4 { public float A, B, C; public IntPtr D; }
其實就很簡單一句話,用IntPtr接收char* 參數就完事了。
InrPtr:用於表示指針或句柄的平台特定類型;接收到IntPtr數據之后,進行一個數據轉換就行了:
//與Int互轉 int i=1; IntPtr p=new IntPtr(i); int ch_i=(int) p; //與string互轉 string str="a"; IntPtr p=Marshal.StringToHGlobalAnsi(str); string s=Marshal.PtrToStringAnsi(p); Marshal.FreeHGlobal(p)