gpt4 book ai didi

c# - 通过反射获取指针值

转载 作者:太空狗 更新时间:2023-10-30 01:15:36 25 4
gpt4 key购买 nike

我有一个 object 类型的实例,从中我知道它是一个指针(可以很容易地用 myobject.GetType().IsPointer 验证)。是否可以通过反射获取指针的值?

到目前为止的代码:

object obj = .... ; // type and value unknown at compile time
Type t = obj.GetType();

if (t.IsPointer)
{
void* ptr = Pointer.Unbox(obj);

// I can obtain its (the object's) bytes with:
byte[] buffer = new byte[Marshal.SizeOf(t)];
Marshal.Copy((IntPtr)ptr, buffer, 0, buffer.Length);

// but how can I get the value represented by the byte array 'buffer'?
// or how can I get the value of *ptr?
// the following line obviously doesn't work:
object val = (object)*ptr; // error CS0242 (obviously)
}


附录 №1: 由于所讨论的对象是值类型 -不是引用类型-,我不能使用 GCHandle::FromIntPtr(IntPtr)其次是 GCHandle::Target获取对象的值...

最佳答案

我想您需要的是 PtrToStructure。像这样:

if (t.IsPointer) {
var ptr = Pointer.Unbox(obj);

// The following line was edited by the OP ;)
var underlyingType = t.GetElementType();
var value = Marshal.PtrToStructure((IntPtr)ptr, underlyingType);
}

关于c# - 通过反射获取指针值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37500414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com