有没有办法从结构中删除未使用的变量?

Is there a way to remove unused variables from a struct?

我有这样的结构

[StructLayout(LayoutKind.Sequential)]
internal struct Context
{
    internal uint ContextFlags;

    private readonly IntPtr Dr0;
    private readonly IntPtr Dr1;
    private readonly IntPtr Dr2;
    private readonly IntPtr Dr3;
    private readonly IntPtr Dr6;
    private readonly IntPtr Dr7;

    private readonly FloatingSaveArea FloatingSave;

    private readonly IntPtr SegGs;
    private readonly IntPtr SegFs;
    private readonly IntPtr SegEs;
    private readonly IntPtr SegDs;

    private readonly IntPtr Edi;
    private readonly IntPtr Esi;
    private readonly IntPtr Ebx;
    private readonly IntPtr Edx;
    private readonly IntPtr Ecx;
    private readonly IntPtr Eax;

    private readonly IntPtr Ebp;
    internal IntPtr Eip;
    private readonly IntPtr SegCs;
    private readonly IntPtr EFlags;
    private readonly IntPtr Esp;
    private readonly IntPtr SegSs;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
    private readonly byte[] ExtendedRegisters;
}

使用下面的pinvoke方法填充数据

[DllImport("kernel32.dll")]
internal static extern bool GetThreadContext(IntPtr hThread, ref Context lpContext);

我只需要访问变量 ContextFlagsEip

理想情况下,我想从结构中删除我不需要的所有其他变量,但是,当我这样做时,Eip 变量不再填充正确的值。

我也试过以下

[StructLayout(LayoutKind.Explicit)]
internal struct Context
{
    [FieldOffset(0)]
    internal uint ContextFlags;

    [FieldOffset(184)]
    internal IntPtr Eip;
}

184的字段偏移量来自

uint offsetEip = (uint) Marshal.OffsetOf(typeof(Context), "Eip");

这也不行

有办法实现吗?也许通过使用 class 而不是结构?

该结构在 Windows 头文件中定义,对应于 Windows API 函数,它假定您将地址传递给 allocated/owned相同大小的完整结构的内存位置。由于 Windows API 函数仅获取一个指针,因此它必须假设您已将指针传递给整个结构,尽管您将只使用其中的两个成员。您可以创建自己的相同大小的结构,以仅公开您需要的两个成员。

当然可以,最后,它只是一个不透明的字节数组,但是你必须确保整个结构大小相同并且匹配当前hardware/software 上下文,因此,只需为 x86 进程这样定义它:

[StructLayout(LayoutKind.Explicit, Size = 716)] // size is 716 for x86
internal struct X86Context
{
    [FieldOffset(0)]
    internal uint ContextFlags;

    [FieldOffset(184)]
    internal IntPtr Eip;
}