简体   繁体   中英

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 ...

Try using GCHandle.Alloc with the second parameter GCHandleType.Pinned . Also method GCHandle.AddrOfPinnedObject might be helpful.

Try these two links:

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);
}

I think you are interested in Marshal.StructureToPtr . I also suggest reading this blog post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM