Wednesday, January 26, 2011

String To IntPtr

Often we required to copy our managed string into unmanaged memory and gets it pointer to pass string's integer pointer (IntPtr) to the unmanaged api. To create a copy of managed string into unmanaged memory call one of the below given static method of Marshal class.

1. Marshal.StringToHGlobalAnsi : Creates the ANSI encoded unmanaged copy of the string.

public static IntPtr StringToHGlobalAnsi (string s)

E.g.
string str = "my string";
IntPtr ptrStr Marshal.StringToHGlobalAnsi(str);

2. Marshal.StringToHGlobalUni : Creates the Unicoded encoded unmanaged copy of the string.

public static IntPtr StringToHGlobalUni (string s)

E.g.
string str = "my string";
IntPtr ptrStr = Marshal.StringToHGlobalUni(str);


Releasing the unmanaged resources
The unamanaged resources are not disposed or released by the garbage collector so we must release the unmanaged resource after its use and to release our unmanaged string from memory we uses another static method Marshal class which is Marshal.FreeHGlobal

public static void FreeHGlobal (IntPtr hglobal)

E.g.
FreeHGlobal(ptrStr);

No comments: