Std :: string in C #?

I thought the problem was in my C ++ function, but I tried this

C ++ function in C ++ dll:

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

C # code:

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

I get an exception that the memory is corrupt, why?

If I remove the std :: string parameter, it works fine, but it does not work with std :: string.

+7
c ++ c # dll
source share
5 answers

std :: string and C # string are incompatible with each other. As far as I know, the C # line corresponds to passing char* or wchar_t* in C ++ with respect to interaction.
One of the reasons for this is that there can be many different implementations in std :: string, and C # cannot assume that you are using any particular one.

+14
source share

Try something like this:

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

You must also specify the appropriate character set (unicode / ansi) in your DllImport attribute.

As an aside, unrelated to your marshalling problem, you can usually pass the string std: as a link to const: const std: string & file name.

+6
source share

It is not possible to output C ++ std :: string in the way you are trying. You really need to write a wrapper function that uses the plain old const char* and translates to std :: string under the hood.

C ++

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

FROM#

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

I know this topic is a bit old, but for future googlers this should work too (without using char * in C ++)

FROM#:

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

C ++:

 bool __declspec( dllexport ) OpenA(std::string file); 
0
source share

std :: wstring and System.string can be compatible through conversion below:

C ++:

 bool func(std::wstring str, int number) { BSTR tmp_str = SysAllocStringLen(str.c_str(), str.size()); VARIANT_BOOL ret = VARIANT_FALSE; // call c# COM DLL ptr->my_com_function(tmp_str, number, &ret); SysFreeString(tmp_str); return (ret != VARIANT_FALSE) ? true : false; } 
0
source share

All Articles