您不能
std::string跨互操作边界传递C ++ 。您不能在C#代码中创建其中之一。因此,您的代码将永远无法工作。
您需要在互操作边界使用互操作友好类型。例如,以null终止的字符数组。当您在同一模块中分配和取消分配内存时,这种方法效果很好。因此,将数据从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);


