c++ DLL和c#之间传递字符串

c++代码

 1 extern "C" _declspec(dllexport) bool get(char*& strPorts)

 2 {

 3     string str = "Hello";

 4     int length = str.size() + 1;

 5     strPorts = newchar[length];

 7     strcpy_s(strPorts, length, str.c_str());

 8     return true;

 9 }

10 extern "C" _declspec(dllexport) bool set(char* str)

11 {

12     cout << str << endl;

13     return true;

14 }

 

c#代码

 1     [DllImport("My.dll")]

 2     public static extern bool get(out IntPtr pstrPorts);

 3     [DllImport("My.dll")]

 4     public static extern bool set(string strPorts);

 5     //调用

 6     IntPtr pStr;

 7     get(out pStr);

 8     System.Console.WriteLine(Marshal.PtrToStringAnsi(pStr));

 9 

10     string str="Hello";

11     set(str);

 

 

因为set里面传递的指针是空的,需要dll来new,百度了好久才找到解决方案。

你可能感兴趣的:(C++)