Search code examples
c#pinvoketypedefunsafe

Can't get around compile error about fixed sized buffers in C#


I'm trying to create some structures in C# to mimic ones from some C++ Microsoft header files. My code is as follows:

[StructLayout(LayoutKind.Sequential)]
unsafe public struct _NotifyData
{
    fixed uint adwData[2];
    public struct Data
    {
        uint cbBuf;
        IntPtr pBuff;
    }
}

[StructLayout(LayoutKind.Sequential)]
public struct PRINTER_NOTIFY_INFO_DATA
{
    public ushort Type;
    public ushort Field;
    public uint Reserved;
    public uint Id;
    public _NotifyData NotifyData;
}

[StructLayout(LayoutKind.Sequential)]
unsafe public struct PRINTER_NOTIFY_INFO
{
    public uint Version;
    public uint Flags;
    public uint Count;
    fixed PRINTER_NOTIFY_INFO_DATA aData[1];  //Compiler complains here!!!
}

The compiler complains about my aData[1] variable in my declaration of struct PRINTER_NOTIFY_INFO. I've encountered a handfull of these and adding fixed to the variable in question and unsafe to the structure declaration seemed to work. Except for this structure that is. The error I get is this:

Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double

Now I can see that the type I'm using is not one of the listed types, but according to this, putting unsafe in front of the struct declaration should allow me to use types other than the ones listed. For some reason it is not letting me.


Solution

  • You just can't declare fixed-size array of custom structs in C#, as the error message and the page you linked to (I suggest you reread it) say.

    EDIT: Removed incorrect info. See David Heffernan's answer for a way to solve this.