leon22
leon22

Reputation: 5649

Convert System::String to char* in function with StringToHGlobalAnsi

I need many conversions in my CLI wrapper from System::String^ to char* and I've written a function, but I can't free the heap space before returning the char*! (get heap errors over the time)

Conversion

char* ManagedReaderInterface::SystemStringToChar(System::String ^source)
{           
    char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(source);

    return str2;
}

I use the function like:

GetSomething(SystemStringToChar(str), value);

Any ideas?!

Upvotes: 1

Views: 4867

Answers (2)

leon22
leon22

Reputation: 5649

In every single method:

IntPtr memHandle = Marshal::StringToHGlobalAnsi(string);

try
{
    char *charStr = static_cast<char*>(memHandle .ToPointer());

    // do something with charStr

    Marshal::FreeHGlobal(memHandle); // free space -> Attention: don't delete it to soon
}
catch
{
    ...
}   

It should be clean now!

Upvotes: 2

JoeG
JoeG

Reputation: 13192

Ultimately, someone needs to be responsible for freeing the memory that your return value is stored in. It can't be your conversion function, as it will return before you want to free the memory.

This is all made easier if you use std::string instead of raw char*s. Try this:

#include <msclr/marshal_cppstd.h>
...     
GetSomething(msclr::interop::marshal_as<std::string>(str).c_str(), value);

Upvotes: 4

Related Questions