What is the best way to send structures containing enum values โ€‹โ€‹through sockets in C

I have many different structures containing enumeration members that I must pass over TCP / IP. While the endpoints are on different operating systems (Windows XP and Linux), which means different compilers (gcc 4.xx and MSVC 2008), both parts of the program use the same header files with type declarations.

For performance reasons, structures should be passed directly (see the code example below) without costly serialization or streaming of elements inside.

So the question is how to ensure that both compilers use the same internal memory representation for enumeration elements (i.e. both use 32-bit unsigned integers). Or if there is a better way to solve this problem ...

//type and enum declaration
typedef enum 
{
    A        = 1,
    B        = 2,
    C        = 3
} eParameter;


typedef enum
{
    READY    = 400,
    RUNNING  = 401,
    BLOCKED  = 402
    FINISHED = 403
} eState;


#pragma pack(push,1)
    typedef struct
    {
        eParameter mParameter;
        eState mState;
        int32_t miSomeValue;
        uint8_t miAnotherValue;
        ...
    } tStateMessage;
#pragma pack(pop)


//... send via socket
tStateMessage msg;
send(iSocketFD,(void*)(&msg),sizeof(tStateMessage));

//... receive message on the other side
tStateMessage msg_received;
recv(iSocketFD,(void*)(&msg_received),sizeof(tStateMessage));

Additionally...

  • Since both endpoints are small endmasks, endianess is not a problem here.
  • And the #pragma package satisfactorily solves alignment problems.

thanks for your answers, Axel

+3
source share
5 answers

I will answer your question pragmatically because you have chosen a relatively risky path after weighing performance indicators against possible shortcomings (at least I hope you have one!).

, .

  • , ( ) .
  • , , .
  • . .
  • , , .
  • !; -)
+1

, , :

, , - , .

, Avro API C. Thrift C API ++, API C, protobuf-c.

+1

. .

, . ? . - , , , , . .

, , . .

? !:)

+1

, , , , 32- int #DEFINE . .

, , . , , . , C99 enums int , , int. , , , :

typedef enum
{
    READY    = 400,
    RUNNING  = 401,
    BLOCKED  = 402,
    FINISHED = 403,
    MAX      = MAX_INT
} eState;

, . , , , gcc , 64- , .

Also check: What is the size of the listing in C?

+1
source

It is highly recommended that you serialize the data in some way or at least use a hardware architecture indicator. Even if you use the same compiler, you may have problems with internal representations of the data (small final, large, etc.).

0
source

Source: https://habr.com/ru/post/1750307/


All Articles