Created
July 23, 2013 00:38
-
-
Save Porges/6058949 to your computer and use it in GitHub Desktop.
Smuggling a GCHandle as an IntPtr.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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