Search code examples
c#unmanaged

How to get unmanaged pointer on an C# object?


I know how to create unmanaged pointer on struct.
But i want to have a unmanaged pointer that will point on an object.

I already know that i need to protect the object from the GC using

GCHandle.Alloc(...);

But i can't find a way to define a pointer ...


Solution

  • You can pin an instance like this:

    GCHandle handle = GCHandle.Alloc(oldList, GCHandleType.Pinned);
    

    Assuming it works, you can then take the address of the pinned object as a type-agnostic pointer, like this:

    IntPtr ptr = handle.AddrOfPinnedObject();
    

    Don't forget to explicitly release the handle before you lose track of it (otherwise the object will remain perpetually pinned):

    handle.Free();
    

    Notice that I said "assuming it works" — not all objects can be pinned and those that can't will throw an exception when you attempt to pin them.

    If you'd like to risk taking the address of a non-pinned object, you can use System.Runtime.CompilerServices.Unsafe to attempt something like this:

    static unsafe void* VeryUnsafeGetAddress(this object obj)
    {
        return *(void**)Unsafe.AsPointer(ref obj);
    }