Monday, February 22, 2010

Marshaling Unions

How to Marshal a Union

You can marshal a union the same way you marshal structures. However, because of the way that unions laid-out into memory, you will need to explicitly set variable positions inside the type.

You can marshal a union in few steps:

  1.
     Create your marshaling type, no matter whether your marshaling type is a managed structure or class. However, you should consider the passing mechanism when working with reference types like classes.
  2.
     Decorate the type with the StructLayoutAttribute attribute specifying LayoutKind.Explicit to control exactly the memory location of every member inside the type.
  3.
     Add your required fields only. Because we are controlling the memory layout explicitly, order of fields is no important.
  4.
     Decorate every field with FieldOffsetAttribute attribute specifying the absolute position -in bytes- of the member from the start of the structure.

Example

Consider the following union:

union SOME_CHARACTER {
      int iCode;
      char cChar;
};

Now, it's the time for the meat of our lesson. The following code snippets defines the marshaling type of our union:

   [StructLayout(LayoutKind.Explicit)]
   public struct SOME_CHARACTER
   {
       // Both members located on the same
       // position in the beginning of the union

       // This is the continer. it is 4 bytes
       [FieldOffset(0)]
       [MarshalAs(UnmanagedType.I4)]
       public int iCode;

       // This is only 1 byte.
       [FieldOffset(0)]
       public char cChar;
   }


Read more: C# Corner

Posted via email from jasper22's posterous