Marshaling a String from C++

I'm having trouble Marshaling a CString from C++ to C#.

My C++ exported function is:

EXPORT_DLL char* getJavascript(){

       *jsArray = const_cast<char*> ( pWindow->returnJS().c_str () );

       cerr << "string is: " << const_cast<char*> ( pWindow->returnJS().c_str () ) << "!" << endl; // output to log file...

       //*jsArray = "this is a test";

        return jsArray[0] ;


My C# function is:

[DllImport ("DLL_Plugin")]
private static extern IntPtr getJavascript();


void updateJS(){

    jsString = Marshal.PtrToStringAnsi(getJavascript());


If I uncomment (//*jsArray = "this is a test";) from the first block, the string is passed just fine and it appears in C# as it should.

Also, the cerr line writes the string to a log file with no problem, so I think this is a problem with the way C# receives the string? I'm not sure. Any help would be appreciated.

The way you're marshaling script side is exactly the same way I do it, and it works fine.

My native functions, though, return a `const char*`. Try doing that and removing all the `const_cast`s.

Ok, my problem was the way I was returning my string to C#, the c_string fell out of scope before I could pass it.

My old C++ function :

*jsArray = const_cast<char*> ( pWindow->returnJS().c_str () );

 return jsArray[0];

My new 'working' C++ function:

const std::string& js = pWindow->returnJS();
char *result = new char[js.size()+1];
strcpy(result, js.c_str());
return result;