开发者

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?!


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);


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜