CptSloth
CptSloth

Reputation: 13

Serialization/Deserialization strategy for byte stream of C structs in C#

I'm working on a Client app, written in C#, which should communicate with a legacy app (let's call it a server). The problem is that the server's API is represented as a bunch of plain old C structs. Every struct has a 4-byte header and the data that follows it. It's just a byte stream.

I understand that this particular binary format is unique (given by the legacy server app). Because of that, it's not possible to use any SerDes libraries like Protocol Buffers, which uses its way of encoding binary data.

PS: We're talking about little-endian only.

This is how the server defines a message:

struct Message1
{
    byte    Size;       // Header 1st byte
    byte    Type;       
    byte    ReqI;       
    byte    Zero;       //Header 4th byte.

    word    UDPPort;    // Actual data starts here.
    word    Flags;      

    byte    Sp0;        
    byte    Prefix;     
    word    Interval;   

    char    Admin[16];  
    char    IName[16];  
};

Upvotes: 1

Views: 371

Answers (1)

bazza
bazza

Reputation: 8414

It sounds like you have fixed sized c structs being sent via a socket connection and you need to interpret those into handy C# classes.

The easiest way may be to do all the message handling in code written in managed C++. In that you’d have a structure that, possibly with a bunch of pragmas, I’m sure could be made to have the same memory layout as the structure being sent through the socket. You would then also define a similar managed c++ class (eg containing managed strings instead of char arrays). You would also write code that converts the struct field by field into one of these managed classes. Wrap the whole thing up in a DLL, and include it in your C# project as a dependency.

The reason for this is because managed C++, weird though it is as a language, is a far easier bridge between unmanaged and managed code and data structures. There’s no need to marshall anything, this is done for you. I’ve used his route to create libraries that make calls into Windows’ hardware discovery facilities, for which there isn’t (or wasn’t) any pre-existing C# library. Using managed C++ code to call the necessary win32 functions was far easier than doing the same thing from C#.

Good luck!

Upvotes: 1

Related Questions