Damir Arh's Corner
Search
Categories
  Development
 .NET
 Batch
 C++
 SQL
 VB6
 Vista
 Web
 Win32
  Downloads
 Amiga
 Articles
 Presentations
 Sources
 Windows
  Personal
 Education
 Software
 Website
Archives
July, 2008 (1)
June, 2008 (1)
April, 2008 (2)
December, 2007 (1)
November, 2007 (3)
July, 2007 (4)
June, 2007 (1)
May, 2007 (2)
March, 2007 (3)
January, 2007 (1)
December, 2006 (4)
October, 2006 (5)
September, 2006 (3)
August, 2006 (2)
June, 2006 (8)
May, 2006 (5)
April, 2006 (1)
March, 2006 (4)
February, 2006 (3)
January, 2006 (3)
March, 2003 (1)
February, 2002 (1)
January, 2002 (2)
August, 2001 (1)
July, 2001 (1)
February, 2001 (1)
December, 2000 (1)
September, 2000 (1)
July, 2000 (1)
Other Sites
Potepanja v naravi (sl)
Picasa Web Albums (sl)
moj-album.com Gallery (sl)
Bolha.com Auctions (sl)
My Game Space
LinkedIn Public Profile
My GamerTag
Sponsored Links
Administration
Sign In
Sunday, May 28, 2006

Marshalling System.String to char* and vice-versa (Development | .NET | C++)

By switching from C# with P/Invoke calls to Managed C++ when implementing a managed wrapper for the ANSI C style library I stumbled upon, I wanted to avoid the tedious and error-prone task of writing the P/Invoke signatures for function calls and user-defined types for the structures they used. As a side result I also managed to avoid most of the advanced marshalling issues with complex data structures.

With simple value types not needing any explicit marshalling only strings need special attention since char* and System::String can’t be implicitly converted between. The Marshal class implements the methods necessary for doing this as demonstrated in the following snippet:

String^ MCPP::Together(String^ first, String^ second)
{
   // marshal managed strings to unamanged memory
   IntPtr firstPtr = Marshal::StringToHGlobalAnsi(first);
   IntPtr secondPtr = Marshal::StringToHGlobalAnsi(second);

   // cast unmanaged buffer to a characer array
   char* firstNative = static_cast<char*>(firstPtr.ToPointer());
   char* secondNative = static_cast<char*>(secondPtr.ToPointer());

   // perform some unmanaged calls
   int bufferSize = strlen(firstNative) + strlen(secondNative) + 4;
   char* resultBuffer = new char[bufferSize];
   sprintf_s(resultBuffer, bufferSize, "%s + %s", firstNative, secondNative);
  
   // marshal unmanaged character array to managed string
   String^ result = Marshal::PtrToStringAnsi(static_cast<IntPtr>(resultBuffer));
  
   // free all unmanaged buffers
   delete[] resultBuffer;
   Marshal::FreeHGlobal(firstPtr);
   Marshal::FreeHGlobal(secondPtr);
  
   // return managed string
   return result;
}

It should be noted that it wouldn’t make any sense switching to unmanaged code to do some string operations only as shown above. This is for demonstration purposes only and you would usually call some unmanaged libraries or the like instead of it. But it is a nice demonstration how cumbersome string operations were in C. If you were doing this once, the sprintf_s function call might have caught your attention. It’s a safe implementation of sprintf which prevents buffer overflows.

Another point worth mentioning is that you have to take care of allocated memory for the conversion since your character array is now allocated on the unmanaged heap. Make sure you use the FreeHGlobal method to do it, not the free (used for freeing memory allocated by *alloc calls – ANSI C style) or delete (used for freeing memory allocated by new calls – C++ style) functions.

To reduce the code overhead of string conversions between managed and unmanaged world you might consider wrapping it into a helper class. This should also help preventing unwanted memory leaks during the conversions.

5/28/2006 1:41:03 PM (Central Europe Standard Time, UTC+01:00)  #  Comments [2]

5/29/2006 12:17:53 PM (Central Europe Standard Time, UTC+01:00)
This site will help with those nasty procedure translations :)

http://www.pinvoke.net/
Mladen
5/29/2006 7:55:15 PM (Central Europe Standard Time, UTC+01:00)
Yes, I know the site. It's a great resource as long as you're working with standard Windows libraries. Unfortunately, I've strayed away from them a bit.
Damir Arh |damir dot arhAT NOSPAMgmail dot com
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Blog Feeds
RSS 2.0 RSS 2.0
Atom 1.0 ATOM 1.0
Fellow Bloggers
 Andrej Tozon
 Dejan Sarka
 Dusan Zupancic
 Matevz Gacnik
 Miha Markic
Disclaimer
The content of this site are my own personal opinions and do not represent my employer's view in anyway. In addition, my thoughts and opinions often change, and as a weblog is intended to provide a semi-permanent point in time snapshot you should not consider out of date posts to reflect my current thoughts and opinions.

Powered by:
newtelligence dasBlog 1.8.5223.2

© 2008 Damir Arh, M. Sc. Send mail to the author(s)

Microsoft Certified Professional
Currently Reading
Currently Playing
Currently Watching