brainfog brainfog - 1 year ago 75
C# Question

c# how to convert array of struct to struct of array

I'm starting with an IntPtr to structured data from a hardware source that sends periodic packets. A thread copies a packet from the Intptr buffer and places byte[] into a queue. Later the queue is read and byte[] is converted to a structure using this answer and becomes a collection (array) of type Packet.

struct Packet {
long time;
int field1;
short field2;

Packet[] array_of_packet;

Without duplicating the structure definition, I would like to use the data as if it was a structure of arrays.

struct ArrayOfPacket {
long[] time;
int[] field1;
short[] field2;

ArrayOfPacket data;

This format allows other functions use them as vectors:

Plot(data.time, data.field1);

Answer Source

If all you want is an easy way to transform to arrays, then just use LINQ:

Plot (array_of_packet.Select(p => p.time).ToArray(),
      array_of_packet.Select(p => p.field1).ToArray());

If you're looking for a magic way to rearrange the data in memory without the cost of copying, then you're out of luck. ;-)