将C#中的string传递给C ++ DLL并返回最简单的例子
我正在尝试使用C#中的C ++ DLL传递string的绝对最简单的例子。
我的C ++看起来像这样:
using std::string; extern "C" { string concat(string a, string b){ return a + b; } } 像一个头像
 using std::string; extern "C" { // Returns a + b __declspec(dllexport) string concat(string a, string b); } 
我的C#是
 [DllImport("*****.dll", CallingConvention = CallingConvention.Cdecl)] static extern string concat(string a, string b); } 
我打电话给:Console.WriteLine(concat(“a”,“b”));
但是这给了一个System.AccessViolationException。 这看起来似乎是最微不足道的事情,但是我完全停留在这个问题上。 当我试图做一个类似的function“添加”,拿了两个双打,并返回一个双倍我没有任何问题。
 你不能通过互操作边界传递一个C ++ std::string 。 你不能在你的C#代码中创build其中的一个。 所以你的代码无法工作。 
您需要在互操作性边界上使用互操作性的types。 例如,以空字符结尾的数组。 当你在同一个模块中分配和释放内存时,效果很好。 所以,从C#传递数据到C ++就足够简单了。
C ++
 void foo(const char *str) { // do something with str } 
C#
 [DllImport("...", CallingConvention = CallingConvention.Cdecl) static extern void foo(string str); .... foo("bar"); 
在另一个方向,你通常希望调用者分配被调用者可以写入的缓冲区:
C ++
 void foo(char *str, int len) { // write no more than len characters into str } 
C#
 [DllImport("...", CallingConvention = CallingConvention.Cdecl) static extern void foo(StringBuilder str, int len); .... StringBuilder sb = new StringBuilder(10); foo(sb, sb.Capacity);