在C#中的std ::string?

我认为这个问题在我的C ++函数中,但是我尝试了这个

在C ++中的C ++函数dll:

bool __declspec( dllexport ) OpenA(std::string file) { return true; } 

C#代码:

 [DllImport("pk2.dll")] public static extern bool OpenA(string path); if (OpenA(@"E:\asdasd\")) 

我得到一个例外,内存是腐败的,为什么?

如果我删除std :: string参数,它工作得很好,但与std ::string不起作用。

std :: string和c#string不兼容。 据我所知,c#string对应于在c ++中传递char*wchar_t*就interop而言。
其中一个原因是std :: string可能有许多不同的实现,而c#不能假定你正在使用任何特定的实现。

尝试这样的事情:

 bool __declspec( dllexport ) OpenA(const TCHAR* pFile) { std::string filename(pFile); ... return true; } 

您还应该在DllImport属性中指定适当的字符集(unicode / ansi)。

顺便说一下,与你的编组问题无关,通常会传递一个std:string作为一个const引用:const std:string&filename。

不可能以你尝试的方式编组C ++ std :: string。 你真正需要做的是写一个包装函数,它使用一个普通的旧的const char*并转换为一个std :: string。

C ++

 extern C { void OpenWrapper(const WCHAR* pName) { std::string name = pName; OpenA(name); } } 

C#

 [DllImport("pk2.dll")] public static extern void OpenWrapper( [In] string name); 

我知道这个主题是一个旧的,但未来的谷歌,这也应该工作(不使用C + + char *)

C#:

 public static extern bool OpenA([In, MarshalAs(UnmanagedType.LPStr)] path); 

C ++:

 bool __declspec( dllexport ) OpenA(std::string file);