While the accepted answer is correct, I wanted to add a little bit to it.
I have grown fond of creating extensions for this so it reads: list1.ToIntPtr()
.
public static class ObjectHandleExtensions
{
public static IntPtr ToIntPtr(this object target)
{
return GCHandle.Alloc(target).ToIntPtr();
}
public static GCHandle ToGcHandle(this object target)
{
return GCHandle.Alloc(target);
}
public static IntPtr ToIntPtr(this GCHandle target)
{
return GCHandle.ToIntPtr(target);
}
}
Also, depending on how much of this you're doing, it might be nice to contain your list in an IDisposable
.
public class GCHandleProvider : IDisposable
{
public GCHandleProvider(object target)
{
Handle = target.ToGcHandle();
}
public IntPtr Pointer => Handle.ToIntPtr();
public GCHandle Handle { get; }
private void ReleaseUnmanagedResources()
{
if (Handle.IsAllocated) Handle.Free();
}
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
}
~GCHandleProvider()
{
ReleaseUnmanagedResources();
}
}
And then you might consume it like this:
using (var handleProvider = new GCHandleProvider(myList))
{
var b = EnumChildWindows(hwndParent, CallBack, handleProvider.Pointer);
}