简体   繁体   中英

How to convert C# struct to C struct?

[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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM