Byte array Marshalling

1k views Asked by At

My application is receiving a struct from another application via UDP socket. The other application is written in C++. The struct has variables of different types. On my application side, I decode the received message from byte array to the desired type and put it in a Dictionary type variable DecodedMessage in the following way:

DecodedMessage.Add("VarName", (float)BitConvertor.ToInt32(Buffer, VarOffset));

Problem is that the values I get are not correct. I believe the problem is that I have to do some kind of Marshaling, but I have no idea how to do it. The C++ application uses a #pragma pack(1) declaration.

2

There are 2 answers

2
T_D On BEST ANSWER

If the C++ application is sending float values you need to use BitConverter.ToSingle instead of ToInt32(). But it is not clear from your question if this is the case or if the C++ app is sending int values that you just want to save as float value.

EDIT

Ok, your C++ app is sending a certain struct, let's assume it looks like this:

struct whatever
{
   int var1;
   float var2;
   byte var3[16];
}

Since you know the structure of the data, you can read it with a BinaryReader like this:

var binReader = new BinaryReader(new MemoryStream(Buffer));
int var1 = binReader.ReadInt32();
float var2 = binReader.ReadSingle();
byte[] var3 = binReader.ReadBytes(16);

Now you can do whatever you want with that data.

0
user891558 On

Instead of marshalling, the UDP application can serialize the object and transfer the message through UDP socket. This is a modern mathod and supported by may C++ libraries (Example: serialization using boost library is very easy and fast to implement.