简体   繁体   English

如何在C#对象上获取非托管指针?

[英]How to get unmanaged pointer on an C# object?

I know how to create unmanaged pointer on struct. 我知道如何在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 我已经知道我需要使用GC来保护对象

GCHandle.Alloc(...);

But i can't find a way to define a pointer ... 但我找不到定义指针的方法......

Try using GCHandle.Alloc with the second parameter GCHandleType.Pinned . 尝试使用GCHandle.Alloc和第二个参数GCHandleType.Pinned Also method GCHandle.AddrOfPinnedObject might be helpful. 方法GCHandle.AddrOfPinnedObject也可能有用。

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: 如果您想冒险获取非固定对象的地址,可以使用System.Runtime.CompilerServices.Unsafe尝试这样的操作:

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

I think you are interested in Marshal.StructureToPtr . 我想你对Marshal.StructureToPtr感兴趣。 I also suggest reading this blog post. 我也建议阅读这篇博文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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