This code is intentionally unsafe (since what you want to do is unsafe, AFAIK CLR / JIT can reorder structures for performance reasons)
Also note that the signature for MemCpy may vary depending on the version of the framework (it is still internal)
For performance reasons, you should cache this delegate correctly.
The idea from this question is here.
unsafe delegate void MemCpyImpl(byte* src, byte* dest, int len); static MemCpyImpl memcpyimpl; public unsafe static void Copy(void* src, void* dst, int count) { byte* source = (byte*)src; byte* dest = (byte*)dst; memcpyimpl(source, dest, count); }
Then forcing your arrays to be byte arrays (actually invalid *, but ignore the details)
public static void ConversionTest() { var bufferType = typeof(Buffer); unsafe { var paramList = new Type[3] { typeof(byte*), typeof(byte*), typeof(int) }; var memcpyimplMethod = bufferType.GetMethod("Memcpy", BindingFlags.Static | BindingFlags.NonPublic, null, paramList, null); memcpyimpl = (MemCpyImpl)Delegate.CreateDelegate(typeof(MemCpyImpl), memcpyimplMethod); } Struct1[] s1Array = { new Struct1() { value = 123456789 } }; var converter = new Struct12Converter { S1Array = s1Array }; var s2Array = new Struct2[1]; unsafe { fixed (void* bad = s2Array) { fixed (void* idea = converter.S2Array) { Copy(bad, idea, 4); } } } }
source share