Search code examples
c#c++pinvoke32bit-64bitunions

Modelling C/C++ unions in C#


I have the task of modelling the following struct in C#:

typedef struct _SHELLEXECUTEINFO {
  DWORD     cbSize;
  ULONG     fMask;
  HWND      hwnd;
  LPCTSTR   lpVerb;
  LPCTSTR   lpFile;
  LPCTSTR   lpParameters;
  LPCTSTR   lpDirectory;
  int       nShow;
  HINSTANCE hInstApp;
  LPVOID    lpIDList;
  LPCTSTR   lpClass;
  HKEY      hkeyClass;
  DWORD     dwHotKey;
  union {
    HANDLE hIcon;
    HANDLE hMonitor;
  } DUMMYUNIONNAME;
  HANDLE    hProcess;
} SHELLEXECUTEINFO, *LPSHELLEXECUTEINFO;

The union could be modelled here as such

[StructLayout(LayoutKind.Explicit)]
struct Union
{
    [FieldOffset(0)]
    IntPtr hIcon;

    [FieldOffset(4)]
    IntPtr hMonitor;
}

This got me thinking...since the size of IntPtr changes from 4 on a 32bit machine, and 8 on a 64bit machine, how do I compensate for this when using FieldOffset, given that the example shows a FieldOffset of 4, for a 32bit machine?


Solution

  • Actually, the way to model a union in C# is to give the same FieldOffset to all members:

    [StructLayout(LayoutKind.Explicit)]
    struct Union
    {
        [FieldOffset(0)]
        IntPtr hIcon;
    
        [FieldOffset(0)]
        IntPtr hMonitor;
    }
    

    This makes the question moot: it doesn't matter how much space each IntPtr takes up because they are sharing it.