Navigation:  Programming Cookbook > External Interfacing > External Field Types >

Unions

Previous pageReturn to chapter overviewNext page

Some C structures contain Unions, which overlay multiple field types on the same memory space, with some tag (discriminated unions) or other method used to decide which field type to use to interpret the data. Normally Dolphin automatically calculates the offset of each field in a structure on the assumption that each field should follow on from the previous one contiguously in memory, after allowing for any packing. This default behaviour can be overridden by specifying fixed offsets, and multiple fields can be defined at the same offset. This allows us to implement unions quite easily, for example:

defineFields

  "Define the fields of the VARDESC structure.

      typedef struct FARSTRUCT tagVARDESC {

          MEMBERID memid;

          OLECHAR FAR* lpstrSchema;

          union {

              unsigned long oInst;

              VARIANT FAR* lpvarValue;  

          } UNION_NAME(u);

          ELEMDESC elemdescVar;    ***

          unsigned short wVarFlags;

          VARKIND varkind;

      } VARDESC;

  *** Renamed to 'elemdesc' for polymorphism with FUNCDESC

  "

  self

      defineField: #memid type: SDWORDField new offset: 0;

      defineField: #lpstrSchema type: (PointerField type: UnicodeString) offset: 4;

      "Note union here"

      defineField: #oInst type: DWORDField new offset: 8;

      defineField: #lpvarValue type: (PointerField type: VARIANT) offset: 8;

      defineField: #elemdesc type: (StructureField type: ELEMDESC) offset: 12;

      defineField: #wVarFlags type: WORDField new offset: 28;

      defineField: #varkind type: SDWORDField new offset: 32.

  self byteSize: 36

 

This definition was in fact originally auto-generated by the Active-X Component Wizard, which always defines unions in this manner. The same technique can be used to implement custom structure packing, as described in the next section.