make IntPtr in C#.NET point to string value

Saher Ahwal picture Saher Ahwal · Jun 18, 2012 · Viewed 22.6k times · Source

I am using a class which has StringHandle field which is an IntPtr value that represents a LPCWSTR in C++.

internal IntPtr StringHandle; // LPCWSTR

say now that I have a String: string x = "abcdefg"

How can I use the String handle to point to the beginning of the String so that it is like C++ LPCWSTR ?

Answer

Eren Ersönmez picture Eren Ersönmez · Jun 18, 2012

You need to copy the string to the unmanaged memory first and then get the IntPtr from that location. You can do so like:

IntPtr strPtr = Marshal.StringToHGlobalUni(x);

also, you need to make sure to free the unmanaged memory:

Marshal.FreeHGlobal(strPtr);

it's best to do all this in a try/finally.