C# – How To Convert Object To IntPtr And Back?

So if I want to pass a list to my callback function through WinApi I use GCHandle

// object to IntPtr (before calling WinApi):
List<string> list1 = new List<string>();
GCHandle handle1 = GCHandle.Alloc(list1);
IntPtr parameter = (IntPtr) handle1;
// call WinAPi and pass the parameter here
// then free the handle when not needed:
handle1.Free();

// back to object (in callback function):
GCHandle handle2 = (GCHandle) parameter;
List<string> list2 = (handle2.Target as List<string>);
list2.Add("hello world");

Thx to David Heffernan

Edit: As noted in the comments, you need to free the handle after use. Also I used casting. It might be wise to use the static methods GCHandle.ToIntPtr(handle1) and GCHandle.FromIntPtr(parameter) like here. I haven’t verified that.

Leave a Comment