1

I am trying to align a C# class with C++ class so I can RPM the structure in C#. The C++ class contains a pad of 0x10 but I can't seem to align my C# class with my C++ class.

C++ Class:

class Value
{
public:
    char pad_0x0000[0x10]; //0x0000
    float current; //0x0010 
    float maximum; //0x0014 
};

My C# Class:

class Value
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
    public byte[] pad_0x0000 = new byte[0x10]; //0x0000
    public float current; //0x0010 
    public float maximum; //0x0014 
};

The issue is that whenever I attempt to get the size of the structure using Marshal.SizeOf I get this error:

Value cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

I may be going at this all wrong. All I'm trying to do is pad by 0x10 so the 2 classes are aligned

Thanks in advance

EDIT: I followed Hans Passant's advice and now it compiles and runs correctly

[StructLayout(LayoutKind.Sequential)]
class Value
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
    public byte[] pad_0x0000 = new byte[0x10]; //0x0000
    public float current; //0x0010 
    public float maximum; //0x0014 
};

but, the value of current is still incorrect which means that they aren't aligned correctly. So my question now is: Isn't this

char pad_0x0000[0x10]; //0x0000

the same size as this

[MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x10)]
public byte[] pad_0x0000 = new byte[0x10]; //0x0000

And if not, then how do I get the equivalent of the C++ pad in c#?

Cow Nation
  • 71
  • 9
  • 1
    If you want to make this a class instead of a struct (why?) then you must apply [StructLayout(LayoutKind.Sequential)] explicitly. The default for a class is LayoutKind.Auto which provides for an optimized, but unpredictable runtime layout. – Hans Passant May 06 '19 at 22:48
  • I did that and now it compiles and runs but it's not giving me the correct value. Which means that they are still not aligned correctly – Cow Nation May 06 '19 at 23:05
  • https://stackoverflow.com/questions/2138890/layout-of-compiled-objects – Hans Passant May 06 '19 at 23:19

0 Answers0