Alex Rivera | Logout

Size of structures in .NET

Asked 2010-03-11T19:51:20.687
9

My problem is to send a structure between a program in C to a C# program.

I made a structure in C#:

public struct NetPoint {
    public float lat; // 4 bytes
    public float lon; // 4 bytes
    public int alt; // 4 bytes
    public long time; // 8 bytes
}

The total size of the structure must be 20 bytes.

When I do a sizeof() in C++ of this structure,

System.Diagnostics.Debug.WriteLine(
    "SizeOf(NetPoint) = " +
    System.Runtime.InteropServices.Marshal.SizeOf(new NetPoint()));

the debug console shows:

SizeOf(NetPoint) = 24

But I expected to have 20 bytes. Why do I see a difference?

Edit
Report

1 Answer

7

Actually, technically the structure must be a minimum of 20 bytes. If you allocate more when sending, the receiver just won't use / copy them. The problem is always underallocation.

That said, I see the problem. Hmm. I think the problem is the last long.... which IMHO gets aligned to eight bytes, injecting four empty bytes before. I think there is a performance penalty for having an eight-byte element not aligned to an eight-byte boundary.

Attach StructLayout attributes to determine the offset of every element manually. Then you should be able to get things in line.

Reference: How to control the physical layout of the data fields in the .NET Framework 2.0

[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct NetPoint {  
    public float lat; // 4 bytes 
    public float lon; // 4 bytes 
    public int alt; // 4 bytes 
    public long time; // 8 bytes 
} 

That at least should align elements to a one-byte boundary. You can go further by defining the exact start of every element, too, if needed.

answered 2010-03-11T19:58:51.900

Your Answer