0

I am not a C++ developer, i need to send data over TCP with a C# client to C++ Server. My native class on C++ is like to this :

class mypack
{
public:
    BYTE ptype;
    BYTE pver;
    BYTE prob;
    mypack()
    {
        ptype = 0;
        pver = 1;
        prob = 8;
    }
};

I don't have any idea about how to pack data in binary format? Could you help me? I need to use marshaling?

Praneeth Peiris
  • 2,008
  • 20
  • 40
panno
  • 9
  • Do you know how to send data over TCP with C#? Apart from that, this link may help you with encoding an object to binary. https://stackoverflow.com/a/18205093/4130869 – Leandro Andrade Sep 06 '18 at 14:38
  • 1
    You can serialize in JSON using Newtonsoft.JSON or use protobuff to speedup the data transfer. JSON is a very common usage and you can serialize on C# and then deserialize o C++ – Igor Quirino Sep 06 '18 at 14:48

3 Answers3

0

This question isn't entirely clear to me, but I see three coherent parts:

How Do I Ensure that an Object is Packed in C++?

std::alignas

If your compiler supports it, use std::alignas. Some don't (GCC 4.8 comes to mind).

__attribute__((packed))

With GCC, you can use the compiler-specific attribute "packed".

#pragma pack(1)

I don't recommend this one, but if you're using VC++ or some GCC versions, you can use a pragma to ensure a struct is packed. c.f. this post.

Use a serialization library

There are plenty. I've heard good things about cereal.

How do I send an object over TCP in C++?

Let's assume you can open a TCP socket and establish a TCP connection. Then, if you're on POSIX, you can use sendto. Just hand it a pointer to your struct, and the sizeof() that struct, and you're good to go.

How do I Deserialize a Packed Object in C++?

If you're interested in deserialization in C++, you'll want recvfrom.

If you're interested in serialization in C#, I'll let someone with more expertise answer.

Dr. Watson
  • 128
  • 2
  • 11
0

There could be several ways to do that. The way I did, is I used 'boost' library to serialize the C++ object. This allows creating the stream of a member data, even if it is a pointer. I created a library (.dll) out of it and wrapped it using VC++.Net to be used by C#. For C# following would be the structure

C++ <---> VC++.Net <---> C#

This allows, C++ common component to be used by both Client and the Server.

Jawad Akhtar
  • 172
  • 9
0

I used BinaryWrited for write on the socket:

 using (var ms = new MemoryStream())
 using (var bw = new BinaryWriter(ms))
{
   //...
    var buffer = ms.ToArray(); 
}
panno
  • 9