Union byte array superimposed on C # StructLayout.Explicit

I want to have a c-style uion type that has a C # struct type.

For some reason, I get an exception every time I allocate the type that I defined. Here is my own type. The main idea is that I have access to the "pointer" of this structure. Unfortunately, I get a TypeLoadException:

Additional information: Failed to load the type 'ManagedTarget.FngPeriodeParameterType' from the assembly 'ManagedTarget, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null', because it contains an object field with an offset of 0 that is incorrectly aligned or overlapped with a field without an object .

What's wrong?

[StructLayout(LayoutKind.Explicit, Size = 16)] unsafe internal struct FngPeriodeParameterType { [FieldOffset(0)] public Byte[] ByteArray; [FieldOffset(0)] public UInt32 Repetitions; [FieldOffset(4)] public Int16 Amplitude; [FieldOffset(6)] public Int16 Offset; [FieldOffset(8)] public Int16 Gain; [FieldOffset(10)] public UInt16 Selection; [FieldOffset(12)] public UInt32 Step; } 
+4
source share
1 answer

If your intention is that ByteArray is raw data, it should be a fixed buffer; at the moment this is just a link to an unrelated byte[] on the heap - and you cannot overlap the link and uint :

 [FieldOffset(0)] public fixed byte ByteArray[16]; 

Working with him can be a pain; Usually I add helper methods like:

 public void ReadBytes(byte[] data) { fixed (byte* ptr = ByteArray) { for (int i = 0; i < 16; i++) data[i] = ptr[i]; } } 
+5
source

Source: https://habr.com/ru/post/1494073/


All Articles