[英]Using cpp code in c# (return custom struct and std:string)
我正在嘗試構建一個包裝程序以在c#代碼中使用cpp代碼,並且我想返回自定義結構(類)作為method2的輸出,並返回std :: string作為method1的輸出,這是我在cpp中的代碼
extern "C" __declspec(dllexport) std::string method1()
{
std::string s;
//Some Code/////////
return s;
}
這是應該返回自定義結構(或類)的方法
extern "C" __declspec(dllexport) MyStruct method2()
{
MyStruct s;
//Some Code//////
return s;
}
我試圖為這兩種方法編寫C#代碼,這是我的C#代碼
[DllImport("<dllPath>", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string method1(); //Exception
[DllImport("<DllPath>")]
public static extern MyStruct method2(); //Compile Error
現在,當我嘗試運行C#代碼時,方法1出現MarshalDirectiveException,而方法2出現編譯錯誤?
在第一個PInvoke中,C ++方法應返回const char *(s.c_str())。 您應該刪除“ [return [...]]”,然后將字符串替換為IntPtr。 然后,您可以使用Marshal.PtrToStringAnsi(ptr)將IntPtr轉換為字符串。 http://msdn.microsoft.com/zh-CN/library/s9ts558h(v=vs.110).aspx可以為您提供幫助。
在第二個PInvoke中,您應該在C#中定義MyStruct(但是我不能更精確,因為我沒有有關MyStruct的信息)。 該鏈接可以為您提供幫助: http : //www.codeproject.com/Articles/66243/Marshaling-with-C-Chapter-Marshaling-Compound-Ty
編輯:感謝hvd的評論,有時最好使用BSTR ,因為使用char *可能很危險!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.