views:

61

answers:

2

my wrapper from managed to unmanaged is handling a lot of data and this function Marshal::StringToHGlobalAnsi would call new for each of them, which is a big hit for me. So my question is :

can I allocate a chunk of unmanaged memory and use it to convert the managed data types to unmanaged by hand.

A: 

Give this a shot.

char *poutputString = (char *)(void *)Marshal::StringToHGlobalAnsi(inputString);
// do something with poutputString here
Marshal::FreeHGlobal(poutputString);

This is the only way I've seen it used. Can you provide a code snippet of the way it's being used in your case?

Ben Burnett
this "Marshal::StringToHGlobalAnsi" does allocate memory inside, that is the problem.
Gollum
Ah, okay. He was referring to a guy calling new, so I misinterpreted.
Ben Burnett
+1  A: 

Assuming all of the characters in the System::String are in the ASCII range, the most basic implementation would be something like:

void ConvertAndCopy(System::String^ ms, char* us)
{
    for (int i(0); i < ms->Length; ++i)
        us[i] = static_cast<char>(ms[i]);

    us[ms->Length] = '\0';
}

// usage example:
System::String^ ms = "Hello world";
char us[12] = "";

ConvertAndCopy(ms, us);

Note that this performs no bounds-checking on the destination array and does not do any character set conversion.

Whether this performs any better than StringToHGlobalAnsi or whether any performance gains are worth the significant increase in complexity (namely, managing your own memory and handling character set conversions), I have no idea.

James McNellis