Code Snippet I : Wrapper for CLR string to native string marshalling

A frequent (too much frequent) need in Managed C++ is going from System::String objects to char* or wchar_t* strings. The boring side of the marshalling is that the memory allocated with the StringToHGlobalxxx functions should be freed with a matching call to FreeHGlobal.

The solution is simple : using the power of C++ destructors we can create a temporary object for the entire time we need the string. Whenever the object goes out of scope, the string is automagically freed.

You can find the code (released to public domain) here.

Please note that assignments (and copy-constructor) are disabled (they are in an empty private method) to preserve the destruction safety (the free is thus execute once and only once).

As an example you can do :

void mystrcpy(char* dest, const System::String __gc* source)
{
strcpy(dest, StringAutoMarshal(source));
}

with no need to manage the marshalling manually.

Comments

One Response to “Code Snippet I : Wrapper for CLR string to native string marshalling”

  1. Xanathar’s Lair » Blog Archive » Code Snippet II : Handy tridimensional vector class for C++ on September 5th, 2005 11:21 pm

    […] class for C++ As you may have seen, I’ve changed the title of a previous post and I have started a series named &#8220 […]

  • About

    A blog about whatever gets on my computer or any other programmable device I own. From Linux to .NET.

  • Social Networking

  •  

    View Marco Mastropaolo's profile on LinkedIn
    www.flickr.com
    This is a Flickr badge showing public photos from Marco Mastropaolo. Make your own badge here.
  • Blogroll