Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround on declaring a unsafe fixed custom struct array?

Is there any workaround for the error CS1663 ("Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double.")?

I need to declare a unsafe fixed array from another blittable custom type struct but I'm stuck in this compiler error.

Showing some code to elucidate the problem below.

struct s1
{
    byte _b1;
    byte _b2;
}

unsafe struct s2
{
    fixed s1 _s1[5]; // CS1663 here...
}

Note that the two structs are blittable, so the error doesn't make any sense for me.

Anyone have any idea about what I could do?

Thanks.

like image 362
andresantacruz Avatar asked Apr 12 '16 05:04

andresantacruz


2 Answers

Another workaround is to either use pointer type fields.

public struct Foo
{
    public byte _b1;
    public byte _b2;
}

public unsafe struct Bar
{
    public int Length;
    public unsafe Foo* Data;
}

Alternately, if your intention was to make a single value type object which contains all of its own data, contiguously (ie, so it can be memcpy'd in unmanaged code) -- then the only way to do that is by not using any arrays at all.

public struct Foo
{
    public byte _b1;
    public byte _b2;
}

public struct Bar1
{
    public Foo F1;
}

public struct Bar2
{
    public Foo F1;
    public Foo F2;
}

public struct Bar3
{
    public Foo F1;
    public Foo F2;
    public Foo F3;
}
like image 72
James Avatar answered Oct 11 '22 13:10

James


It's a restriction of fixed size buffers.

The fixed array can take any of the attributes or modifiers that are allowed for regular struct members. The only restriction is that the array type must be bool, byte, char, short, int, long, sbyte, ushort, uint, ulong, float, or double.

You can use only that types but not combination (like struct contains only that types). There is no difference if your type bittable or not. You just can't use it.

Then you can't use your custom struct for the fixed size buffer.

Workaround? Mmmm, yes, may be. You can change your code structure and use something like this:

unsafe struct s2
{
    fixed byte _b1[5]; 
    fixed byte _b2[5]; 
}
like image 28
Vadim Martynov Avatar answered Oct 11 '22 13:10

Vadim Martynov