views:

490

answers:

4

I'm developing an app in C++/CLI and have a csv file writing library in unmanaged code that I want to use from the managed portion. So my function looks something like this:

bool CSVWriter::Write(const char* stringToWrite);

...but I'm really struggling to convert my shiny System::String^ into something compatible. Basically I was hoping to call by doing something like:

if( m_myWriter->Write(String::Format("{0}",someValueIWantToSave)) )
{
    // report success
}
+4  A: 
using namespace System::Runtime::InteropServices;
const char* str = (const char*) (Marshal::StringToHGlobalAnsi(managedString)).ToPointer();

From Dev Shed.

mcandre
+1/Accepted: Thanks very much!
Jon Cage
Missing Marshal::FreeHGlobal(...); which can result in memory leak.
Cedrik
@Cedrik, then post a better version of my code.
mcandre
A: 

As mcandre mentions, Marshal::StringToHGlobalAnsi() is correct. But don't forget to free the newly allocated resource with Marshal::FreeHGlobal(), when the string is no longer in use.

Alternatively, you can use the msclr::interop::marshal_as template to create the string resource and automatically release it when the call exits the resource's scope.

Steve Guidi
+1  A: 

There's a list of what types need which conversion in the overview of marshalling in C++.

Jon Cage
A: 

hi Steve,

Marshal::FreeHGlobal() needs an argument. If I use mcandre's code, what should I use for the argument?

Thanks a billion, Ben