Layout.Explicit with managed code for UNION structs

  • Thread starter Fuzzy via .NET 247
  • Start date
F

Fuzzy via .NET 247

I have a struct that I would like to control the field layout on in the same manner of UNION structs in C++.
This is not for passing data to unmanaged code, it is to save memory space because field X will either be short integer or double, and other info in the struct can be used to determine if X should be interpreted as short integer or double.

I have found the docs for [StructLayout(LayoutKind.Explicit)] and for [FieldOffset(0)].

However, one doc state that these fields only control marshalling to unmanged code and does not impact managed storage, while another doc simply states that these attributes may be used to control field layouts.

Does anyone know how this is really implemented? I would like to use it to reduce my memory requirements with large arrays of this struct.
 
C

cody

IIRC, you *can* directly control the storagelayout with these attributes,
but .NET does't allow overlapping of fields to maintain type safety, that
is, you cannot use this to implement a UNION.
If you want to interpret a certain field as another datatyp use properties
which make use of the Marshal class or Bitconverter to reinterpret existing
data fields.

Fuzzy via .NET 247 said:
I have a struct that I would like to control the field layout on in the
same manner of UNION structs in C++.
This is not for passing data to unmanaged code, it is to save memory space
because field X will either be short integer or double, and other info in
the struct can be used to determine if X should be interpreted as short
integer or double.
I have found the docs for [StructLayout(LayoutKind.Explicit)] and for [FieldOffset(0)].

However, one doc state that these fields only control marshalling to
unmanged code and does not impact managed storage, while another doc simply
states that these attributes may be used to control field layouts.
Does anyone know how this is really implemented? I would like to use it
to reduce my memory requirements with large arrays of this struct.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top