I'm having some trouble with getting bytes of a C# struct sent over a TCP socket to a C++ client to read properly. Here are the structs...
Struct in C#
public struct TankBattleStateData
{
    public int playerID;
    public float currentHealth;
    public Vector3 position;
    public Vector3 forward;
    public Vector3 cannonForward;
    public int canFire;
    public int tacticalCount; 
}
Struct in C++
struct TankBattleStateData
{
    int playerID;
    float currentHealth;
    float position[3];
    float forward[3];
    float cannonForward[3];
    int canFire;
    int tacticalCount;
};
The transmission process is as follows...
- Use System.Runtime.InteropServices.Marshalto get an array of C# bytes representing the struct
- Feed array of bytes into Socket.Send to send to C++ client
- Client, upon receipt of bytes, does a memcpy of the bytes received to an unsigned chararray on the heap, which is resized upon before copying if needed- There are some checks like verifying the number of bytes read, but nothing particularly robust in place.
 
- To read its contents, the client casts pointer to the char array as TankBattleStateData *and dereferences it to accesses its fields.
I find that consistently, the last field, tacticalCount is not the same value on the C++ client as it was on the C# client. For example, I'll send 1 from the server and get 81742424 back on client.
Environment
OS: Windows 10 x64
Server: C# w/ .NET Framework 2.0 (Unity3D 5.3.2f1)
Client: C++ w/ MSVC++14
What I'd Like To Know
- What am I doing wrong? ;)
- More specifically, what am I doing wrong on the client? I set up a C# client and it seems to have no problem receiving the data, unlike the C++ client.
 
- Are there existing libraries that would make my life easier?
One hiccup I've had is that the C# bool is marshaled as 4 bytes, rather than 1 byte, which is the size of a bool in MSVC++14. I'd like to use a bool, but in an attempt to reduce the number of possible problems, I'm using an int for now.
 
     
     
    