Marshalling the value of a char* ANSI string DLL API parameter into a C# string

Posted by Brian Biales on Geeks with Blogs See other posts from Geeks with Blogs or by Brian Biales
Published on Thu, 03 Jun 2010 18:35:37 GMT Indexed on 2010/06/03 18:44 UTC
Read the original article Hit count: 349

Filed under:

For those who do not mix .NET C# code with legacy DLL's that use char* pointers on a regular basis, the process to convert the strings one way or the other is non-obvious.

This is not a comprehensive article on the topic at all, but rather an example of something that took me some time to go find, maybe it will save someone else the time.

I am utilizing a third party too that uses a call back function to inform my application of its progress.  This callback includes a pointer that under some circumstances is a pointer to an ANSI character string.  I just need to marshal it into a C# string variable.  Seems pretty simple, yes?  Well, it is, (as are most things, once you know how to do them).

The parameter of my callback function is of type IntPtr, which implies it is an integer representation of a pointer.  If I know the pointer is pointing to a simple ANSI string, here is a simple static method to copy it to a C# string:

private static string GetStringFromCharStar(IntPtr ptr)
{
   
return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptr);
}

The System.Runtime.InteropServices is where to look any time you are mixing legacy unmanaged code with your .NET application. 

© Geeks with Blogs or respective owner