c#将struct转换为int

0 c# int struct

考虑以下结构:

[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];
}
Run Code Online (Sandbox Code Playgroud)

以下代码:

Context ctx = new Context{ ContextFlags = 0x10007 };
Run Code Online (Sandbox Code Playgroud)

现在,我想将此结构代表(ctx)转换为int类型.

int x = (int)ctx;
Run Code Online (Sandbox Code Playgroud)

上述方法不起作用,有人会想到这种转换发生的正确方法吗?

谢谢,

埃文

Mat*_*ira 6

我怀疑你打算调用使用这种结构的Windows API方法.也许甚至这种方法.在这种情况下,.NET marshaller将为您处理此问题.

[DllImport("kernel32.dll")]
public static extern bool GetThreadContext(IntPtr thread, ref CONTEXT context);
Run Code Online (Sandbox Code Playgroud)

请注意,您使用ref关键字传递结构.marshaller将负责创建一个指向结构的非托管指针,并将其传递给被调用的方法.如果方法修改结构的数据,它还将处理指针.