Search code examples
c++c++-climarshalling

Crash on returning a System::String that was marshalled from a native C++ call


I have a native C++ dll which I call from a managed c++ dll which is called from a C# application.

The function in the native dll looks something like this:

std::string NativeClass::Test()
{
    return std::string("some string");
}

The managed C++ function that calls it looks something like this

String ^ ManagedClass::Test()
{
    std::string temp = this->_native->Test();
    String^ sRet = msclr::interop::marshal_as<String^>(temp);

    return sRet; // crashes here !!!
}

However, on executing the return statement, the application crashes with an error like

Debug Assertion Failed!
debug_heap.cpp
Line 980
Expression: __acrt_first_block == header

I looked all over Stackoverflow but I've not solved it yet. Any ideas?


Solution

  • Hans helped solved this. It was indeed a mismatch between the CRT versions in the native dll and managed dll. I was sure I had already checked this but obviously missed it. The code otherwise works as is. Thanks.