jM2.me
jM2.me

Reputation: 3969

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.

Upvotes: 2

Views: 456

Answers (1)

JaredPar
JaredPar

Reputation: 754575

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

Upvotes: 6

Related Questions