I am trying to deserialize a byte array to a struct.
Here is my deserialization function:
void RawDeserialize(byte[] bytearray, object obj)
{
int len = Marshal.SizeOf(obj);
IntPtr i = Marshal.AllocHGlobal(len);
Marshal.Copy(bytearray, 0, i, len);
obj = Marshal.PtrToStructure(i, obj.GetType());
Marshal.FreeHGlobal(i);
}
I call it with
RawDeserialize(outarr, outbuf);
Where outarr is a byte array of length 22 and outbuf is my struct which looks like this:
[StructLayout(LayoutKind.Sequential,Size =22)]
public struct ID_OUTPUT
{
public HEADER_OUTPUT hdr; //Another struct size=8
public byte bType;
public byte bRunning;
[MarshalAs(UnmanagedType.ByValTStr,SizeConst = 8)]
public string softwareName;
public short softwareVersion;
}
When I step-through debug in my deserialization function, obj is filled with correct values, but on return outbuf is filled with zeroes (or is never assigned to because I originally initialize everything to zero).
My initial thought is the object is not being passed by reference, but I assumed this should work because I found this deserialization function on another SO question (which I do not have the link for anymore).
So then I try to use the ref keyword, but then I get an error cannot convert from ref ID_OUTPUT to ref object.