获取非显式字段偏移 [英] Obtain non-explicit field offset

查看:73
本文介绍了获取非显式字段偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

[StructLayout(LayoutKind.Sequential)]
class Class
{
    public int Field1;
    public byte Field2;
    public short? Field3;
    public bool Field4;
}

如何获取 Field4 从类数据(或对象标头)的开头开始?

要说明:

How can I get the byte offset of Field4 starting from the start of the class data (or object header)?
To illustrate:

Class cls = new Class();
fixed(int* ptr1 = &cls.Field1) //first field
fixed(bool* ptr2 = &cls.Field4) //requested field
{
    Console.WriteLine((byte*)ptr2-(byte*)ptr1);
}

在这种情况下,由于运行时实际移动,因此产生的偏移为5 Field3 到类型的末尾(并将其填充),可能是因为其类型是通用的。我知道这里有 Marshal.OffsetOf ,但是它返回的是非托管的偏移量,而不是托管的。

The resulting offset is, in this case, 5, because the runtime actually moves Field3 to the end of the type (and pads it), probably because it its type is generic. I know there is Marshal.OffsetOf, but it returns unmanaged offset, not managed.

如何检索此内容从 FieldInfo 实例偏移?是否有用于.NET的方法,还是我必须编写自己的方法,同时考虑所有异常(类型大小,填充,显式偏移量等)?

How can I retrieve this offset from a FieldInfo instance? Is there any .NET method used for that, or do I have to write my own, taking all the exceptions into account (type size, padding, explicit offsets, etc.)?

推荐答案

通过 TypedReference.MakeTypedReference 的一些技巧,可以获取对该字段的引用以及对对象的数据,然后减去。该方法可以在 SharpUtils 中找到。

With some tricks around TypedReference.MakeTypedReference, it is possible to obtain the reference to the field, and to the start of the object's data, then just subtract. The method can be found in SharpUtils.

这篇关于获取非显式字段偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆