From what I understand, when assigning a struct variable to another, the first is usually copied instead of creating a link:
public struct MYSTRUCT1 { public byte val1; }
This works fine, output:
1 2
However, if I have a byte [] inside my structure, this behavior changes:
public struct MYSTRUCT1 { public byte[] val1; }
This is the conclusion:
2 2
How can i avoid this? I really need to work with a copy of the whole structure, including any byte arrays.
Thanks! ♪
Edit: Thanks for your help! To deep copy my structure, Im now uses this code:
public static object deepCopyStruct(object anything, Type anyType) { return RawDeserialize(RawSerialize(anything), 0, anyType); } public static object RawDeserialize(byte[] rawData, int position, Type anyType) { int rawsize = Marshal.SizeOf(anyType); if (rawsize > rawData.Length) return null; IntPtr buffer = Marshal.AllocHGlobal(rawsize); Marshal.Copy(rawData, position, buffer, rawsize); object retobj = Marshal.PtrToStructure(buffer, anyType); Marshal.FreeHGlobal(buffer); return retobj; } public static byte[] RawSerialize(object anything) { int rawSize = Marshal.SizeOf(anything); IntPtr buffer = Marshal.AllocHGlobal(rawSize); Marshal.StructureToPtr(anything, buffer, false); byte[] rawDatas = new byte[rawSize]; Marshal.Copy(buffer, rawDatas, 0, rawSize); Marshal.FreeHGlobal(buffer); return rawDatas; }
It must be called like this:
MYSTRUCT1 test2 = (MYSTRUCT1)deepCopyStruct(test1, typeof(MYSTRUCT1));
Everything seems to be working fine, although Im aware that this is dirty code.
However, since there are more than 50 byte[] several other structures in them that work with, there is too much work to write Copy() / Clone() methods for each of them.
Suggestions for better code are, of course, very welcome.