I need to convert a struct to bytes so that I can send or receive it over a network.
Let's say the struct is something like below:
struct Info
{
unsigned int Age;
char Name[];
};
I have the equivalent struct in C# sharp which is:
[StructLayout(LayoutKind.Sequential)]
public struct Info
{
public uint Age;
public string Name;
};
To convert the C# struct to byte I use the this method:
public Byte[] GetBytes(Info info)
{
int size = Marshal.SizeOf(info);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(info, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
And to Convert the received bytes to C++ struct I use this method:
Info GetInfo(const char* bytes)
{
Info info;
memcpy(&info, bytes, sizeof(info));
return info;
}
My problem is that the Age field of the struct converts very well but the Name field never is what has been sent.
Update
I can easily convert a string to bytes using the code below and send it from c# client app to c++ server app.
byte[] buffer = Encoding.UTF8.GetBytes(text + "\0");
so I decided to change the C# struct as below:
[StructLayout(LayoutKind.Sequential)]
public struct Info
{
public uint Age;
public byte[] Name;
};
but in this case the GetBytes() method crashes.
CMsg. I'm confused. In any case, the size of the struct in C++ is implementation defined, I believe (in particular because you're using the "C struct hack"). The name is of a variable length. In C#,stringmembers are just references to the actual strings allocated on the heap, so you'll have to do a lot more legwork than merely copying the struct's bytes, but also those of the string.