C# 将 struct 转换为 int
考虑以下结构:
[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;
上面的方法行不通,有人能想到进行这种转换的正确方法吗?
谢谢你,
埃文
Consider the following 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];
}
And the following code:
Context ctx = new Context{ ContextFlags = 0x10007 };
Now, I would like to convert this struct representative (ctx) into type int.
int x = (int)ctx;
The above method will not work, can someone think of the correct way for this conversion to take place?
Thank you,
Evan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑您计划调用使用 这种方法。在这种情况下,.NET 编组器将为您处理此问题。
请注意,您使用
ref
关键字传递结构。编组器将负责创建一个指向该结构的非托管指针并将其传递给被调用的方法。如果该方法修改结构的数据,它还将处理将指针作为结构返回。I'm suspicious that you plan on calling a Windows API method that uses this structure. Perhaps even this method. In this case, the .NET marshaller will handle this for you.
Notice that you pass the structure using the
ref
keyword. The marshaller will take care of creating an unmanaged pointer to the structure and passing it on to the called method. It will also handle bring the pointer back as a structure should the method modify the structure's data.