std::string in C#?

I thought the problem is inside 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 great,but with std::string it doesnt work.


std::string and c# string are not compatible with each other. As far as I know the c# string corresponds to passing char* or wchar_t* in c++ as far as interop is concerned.
One of the reasons for this is that There can be many different implementations to std::string and c# can't assume that you're using any particular one.


Try something like this:

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

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

As an aside, unrelated to your marshalling problem, one would normally pass a std:string as a const reference: const std:string& filename.


It's not possible to marshal a C++ std::string in the way you are attempting. What you really need to do here is write a wrapper function which uses a plain old const char* and converts to a std::string under the hood.

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);

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

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;
}