I'm working on a project and this came to my mind: I have a struct with an id, and an array inside:
struct Str
{
public uint id;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] array;
}
Then I'd like to allocate it with a random size array:
var rnd = new Random();
var str = new Str() { id = 1, array = new byte[rnd.Next(4)] };
int size = Marshal.SizeOf(str);
IntPtr p = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, p, true);
The problem is the struct will always be this random, the problem must be with the allocation or something. The last line gives ArgumentException
when the array size is not 4.
Please help me to find out how to do this. Thanks.