I am trying to copy an array of Struct1
into an array of Struct2
(same binary representation) the fastest way possible.
I have defined an union to convert between Struct1[]
and Struct2[]
but when I call Array.Copy I get an exception saying the array is the wrong type. How can I circumvent that? Buffer.BlockCopy only accepts primitive types.
Here is the code:
[StructLayout(LayoutKind.Explicit)]
public struct Struct12Converter
{
[FieldOffset(0)]
public Struct1[] S1Array;
[FieldOffset(0)]
public Struct2[] S2Array;
}
public void ConversionTest()
{
var s1Array = new{new Struct1()}
var converter = new Struct12Converter{S1Array = s1Array};
var s2Array = new Struct2[1];
Array.Copy(converter.S2Array,0,s2Array,0,1) //throws here
//if you check with the debugger, it says converter.S2Array is a Struct1[],
//although the compiler lets you use it like a Struct2[]
//this has me baffled as well.
}
To give more details:
I wanted to experiment to see if working with a mutable struct and changing the value of its fields had different performance characteristics compared to working all the time using the same immutable struct. I think it should be similar but I thought it was worth a measurement. The underlying application would be a low latency socket library where I currently use ArraySegment<byte>
-based socket APIs. It so happens that in the SocketAsyncEventArgs
api, setting the BufferList
property triggers an array copy which is where my 'experiment' fails (i have an array of MutableArraySegment
which I cannot convert to ArraySegment[]
through the same method as before, thus making my comparison pointless).