将struct转换为int
本文关键字:int 转换 struct | 更新日期: 2023-09-27 18:04:38
考虑以下结构体:
[StructLayout(LayoutKind.Sequential)]
struct CONTEXT
{
public UINT ContextFlags;
unsafe fixed byte unused[160];
public uint Ebx;
public uint Edx;
public uint Ecx;
public uint Eax;
unsafe fixed byte unused2[24];
}
和以下代码:
Context ctx = new Context{ ContextFlags = 0x10007 };
现在,我想把这个结构代表(ctx)转换成int类型。
int x = (int)ctx;
上面的方法将不起作用,有人能想到正确的方法来进行这种转换吗?
谢谢你,艾凡
我怀疑您计划调用使用此结构的Windows API方法。也许甚至是这种方法。在这种情况下,. net编组程序将为您处理此问题。
[DllImport("kernel32.dll")]
public static extern bool GetThreadContext(IntPtr thread, ref CONTEXT context);
注意,您使用ref
关键字传递该结构。编组程序将负责创建指向结构的非托管指针,并将其传递给被调用的方法。如果该方法修改了结构体的数据,它还会处理将指针恢复为结构体。