如何将 C# 结构体转换为 C 结构体?
[StructLayout(LayoutKind.Sequential, Size = 280), Serializable]
public struct AESContext
{
/// int nr;
[MarshalAsAttribute(UnmanagedType.I4, SizeConst = 4)]
public int nr;
/// unsigned long *rk;
[MarshalAsAttribute(UnmanagedType.U4, SizeConst = 4)]
public uint rk;
// unsigned long buf[68];
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 68)]
public uint[] buf;
}
这是我迄今为止拥有的 C# 结构。每个字段上方的注释都是用 C 语言键入的。 如果有人可以验证,我会很高兴。
[StructLayout(LayoutKind.Sequential, Size = 280), Serializable]
public struct AESContext
{
/// int nr;
[MarshalAsAttribute(UnmanagedType.I4, SizeConst = 4)]
public int nr;
/// unsigned long *rk;
[MarshalAsAttribute(UnmanagedType.U4, SizeConst = 4)]
public uint rk;
// unsigned long buf[68];
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 68)]
public uint[] buf;
}
This is C# struct I have so far. Comment above each field is type in C.
I would love if someone could verify.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您正在尝试获取成员内容中定义的 C 结构的 C# 结构。如果是这样,那么我相信您需要进行以下
基本更改
StructLayout
中指定SizeConst
除非您尝试创建一个大小不同(通常)大于它的结构内容。这样做并不常见。MarshalAs
IntPtr
或UIntPtr
来 PInvoke 指针类型。它们的大小在 32 和 64 位平台之间有适当的变化It sounds like you're trying to get the C# struct for the C struct defined in the member contents. If so then I believe you want the following
Basic changes
SizeConst
inStructLayout
unless you are trying to create a struct whose size is different (typically) bigger than it's contents. It's not very common to do thisMarshalAs
isn't usually needed for primitive typesIntPtr
orUIntPtr
to PInvoke pointer types. They vary properly in size between 32 and 64 bit platforms