Is a C# struct with a single field equivalent to the standalone type of the field in unmanaged memory?

72 Views Asked by At

For example, is the unmanged memory layout of this struct:

public struct MyStruct<T>
  where T: unmanaged
{
    public T pointer;
}

the same as a plain T?

Also, does they behave in the same way when calling Marshal.PtrToStructure and Marshal.StructureToPtr? That is, will this work?

MyStruct<int> myStruct;
IntPtr pointer = Marshal.AllocHGlobal(Marshal.SizeOf(MyStruct<int>));
Marshal.StructureToPtr(myStruct, pointer, false);
int myStructField = Marshal.PtrToStructure<int>(pointer);
1

There are 1 best solutions below

0
Charlieface On BEST ANSWER

This is theoretically dependent on which build of the CLR you have. Generally yes, in managed memory a struct is represented by a sequential set of fields. However, especially with local variables, individual fields may be placed into registers or other places (or even optimized away), and with multiple fields reordering may also happen.

And you can never rely on a particular implementation not changing from version to version.

Theoretically, a conforming implementation of the CLR is free to arrange memory in any way it sees fit. My private implementation of .NET stores data on the moon, which is made of cheese. (The stack is made of pizza boxes with hand-written notes, in case you were wondering).


As far as interop is concerned, structs are always marshalled in a defined way. The StructLayoutAttribute is respected: it is part of the specification and not likely to change. Note that if you do not specify the attribute then the CLR is free to reorder or repack it, which is why you should always specify it for interop code.

So if you specify LayoutKind.Sequential then the fields will be aligned beginning at offset 0, and packed according to the bitness of the application (or as specified).