Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It can be done with unsafe code too, although it restricts the context under which your program can run, and, naturally, introduces the possibility of security flaws. The advantage is that you cast directly from an array to the structure using pointers and it's also maintenance-free if you are only going to add or remove fields from the struct. However, accessing the arrays require using the fixed-statement as the GC can still move the struct around in memory when it's contained in an object.</p> <p>Here's some modified code of an unsafe struct I used for interpreting UDP packets:</p> <pre><code>using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] public unsafe struct UnsafePacket { int time; short id0; fixed float acc[3]; short id1; fixed float mat[9]; public UnsafePacket(byte[] rawData) { if (rawData == null) throw new ArgumentNullException("rawData"); if (sizeof(byte) * rawData.Length != sizeof(UnsafePacket)) throw new ArgumentException("rawData"); fixed (byte* ptr = &amp;rawData[0]) { this = *(UnsafePacket*)rawPtr; } } public float GetAcc(int index) { if (index &lt; 0 || index &gt;= 3) throw new ArgumentOutOfRangeException("index"); fixed (UnsafePacket* ptr = &amp;acc) { return ptr[index]; } } public float GetMat(int index) { if (index &lt; 0 || index &gt;= 9) throw new ArgumentOutOfRangeException("index"); fixed (UnsafePacket* ptr = &amp;mat) { return ptr[index]; } } // etc. for other properties } </code></pre> <p>For this kind of code it is extremely important to check that the length of the array perfectly matches the size of the struct, otherwise you'll open for some nasty buffer overflows. As the <em>unsafe</em> keyword has been applied to the whole struct, you don't need to mark each method or codeblock as separate <em>unsafe</em> statements.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload