Skip to content

Instantly share code, notes, and snippets.

@Porges
Created July 23, 2013 00:38
Show Gist options
  • Save Porges/6058949 to your computer and use it in GitHub Desktop.
Save Porges/6058949 to your computer and use it in GitHub Desktop.
Smuggling a GCHandle as an IntPtr.
using System;
using System.Runtime.InteropServices;
class Foo
{
}
class Program
{
static IntPtr AllocAndGetPointer()
{
var foo = new Foo();
var gcHandle = GCHandle.Alloc(foo);
return (IntPtr)gcHandle;
}
static Foo RetrieveObjectFromPointer(IntPtr ptr)
{
var handle = GCHandle.FromIntPtr(ptr);
var foo = (Foo) handle.Target;
handle.Free(); // depending on if you need it later
return foo;
}
static void Main(string[] args)
{
var ptr = AllocAndGetPointer();
// pass ptr into some native method, then in callback:
var foo = RetrieveObjectFromPointer(ptr);
Console.WriteLine(foo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment