DrCocoa
DrCocoa

Reputation: 47

Calling a native c++ dll with std::string argument from c++/cli

I have a native c++ dll which I am trying to call from a c++/cli project. Here's the dll's function

extern "C"
{
   int DLL_EXPORT Add(std::string s1, std::string s2, std::string s3)
   {
     [do stuff]
   }
}

Here's the reference in c++/cli:

using namespace System::Runtime::InteropServices;
[DllImport("my_dll.dll")]
extern "C" int Add(std::string, std::string, std::string);

When I call the function, I marshal the String^ objects to std::string:

Add(msclr::interop::marshal_as<std::string>(stringA),
            msclr::interop::marshal_as<std::string>(stringB),
            msclr::interop::marshal_as<std::string>(stringC));

I get an access violation exception when the call to the DLL is made.

Upvotes: 0

Views: 1242

Answers (1)

EmDroid
EmDroid

Reputation: 6046

Is the DLL and the CLI compiled with the same compiler? In general, different compilers can have different definitions of std::string which can cause the error.

Therefore I wouldn't recommend in general to use std::string or any compiler specific types in DLL interface.

I guess that was the reason you make the function extern "C". If it doesn't work without extern "C", it will most likely not work (because of different mangling rules, which imply either different compiler or at least different std::string definition).

In this case I would prefer to create a wrapping function which takes const char * pointers.

Upvotes: 1

Related Questions