Note that there are some explanatory texts on larger screens.

plurals
  1. POC# StructLayout/FieldOffset and indexing in arrays
    text
    copied!<p>I'm having a bit of a problem using FieldOffset correctly with arrays. The code below is an example where it doesn't work correctly for me:</p> <pre><code>[StructLayout(LayoutKind.Explicit)] public struct IndexStruct { [FieldOffset(0)] public byte[] data; [FieldOffset(0)] public short[] idx16; [FieldOffset(0)] public int[] idx32; } </code></pre> <p>If I for example sets the array named "data" to a serialized byte array and then try to retrieve data as shorts using the "idx16" field the indexing is still aligned as a byte[]. Meaning that idx16<a href="https://stackoverflow.com/questions/619041/what-is-the-fastest-way-to-convert-a-float-to-a-byte/619307#619307">1</a> fetches the second byte in data, not the second 16bit word (byte 2 and 3). If I do the inverse I index shorts instead of bytes, meaning that the offset alignment is inherited from the source data. My question, is there a way to work around this? I know that I can compensate the index value by multiplying with the size of the element, but is there another way?</p> <p><a href="https://stackoverflow.com/questions/619041/what-is-the-fastest-way-to-convert-a-float-to-a-byte/619307#619307">Here</a> is an answer I found here on StackOverflow, but when trying that code it turned out that it wasn't working properly. Tried it out using a Unit test in VS with the following code without any success: </p> <pre><code>[TestMethod()] public void SumTest() { float[] fArr = {2.0f, 0.5f, 0.0f, 1.0f}; MemoryStream ms = new MemoryStream(); for (int i = 0; i &lt; fArr.Length; i++) { ms.Write(BitConverter.GetBytes(fArr[i]), 0, sizeof(float)); } byte[] buff = ms.ToArray(); double expected = 3.5f; double actual = Sum(buff); Assert.AreEqual(expected, actual); } </code></pre> <p>Many thanks in advance!</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