如何将 C# 结构体转换为 C 结构体?

发布于 2025-01-06 13:08:08 字数 501 浏览 4 评论 0原文

[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

喜爱皱眉﹌ 2025-01-13 13:08:08

听起来您正在尝试获取成员内容中定义的 C 结构的 C# 结构。如果是这样,那么我相信您需要进行以下

[StructLayout(LayoutKind.Sequential), Serializable]
public struct AESContext
{
    /// int nr; 
    public int nr;

    /// unsigned long *rk;
    public UIntPtr rk;

    // unsigned long buf[68];
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 68)]
    public uint[] buf;
}

基本更改

  • 不要在 StructLayout 中指定 SizeConst 除非您尝试创建一个大小不同(通常)大于它的结构内容。这样做并不常见。
  • 原始类型通常不需要 MarshalAs
  • 使用 IntPtrUIntPtr 来 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

[StructLayout(LayoutKind.Sequential), Serializable]
public struct AESContext
{
    /// int nr; 
    public int nr;

    /// unsigned long *rk;
    public UIntPtr rk;

    // unsigned long buf[68];
    [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 68)]
    public uint[] buf;
}

Basic changes

  • Don't specify SizeConst in StructLayout 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 this
  • MarshalAs isn't usually needed for primitive types
  • Use IntPtr or UIntPtr to PInvoke pointer types. They vary properly in size between 32 and 64 bit platforms
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文