1

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.

Attila
  • 63
  • 2
  • 6
  • 1
    You should also check out [this question](http://stackoverflow.com/questions/5902103/how-do-i-marshal-a-struct-that-contains-a-variable-sized-array-to-c) – D Stanley Jun 16 '14 at 21:01
  • Missed that. So I have to use IntPtr to the array instead of the array itself. Thank you. – Attila Jun 16 '14 at 21:23

0 Answers0