Using ntohl on Struct or Union

925 views Asked by At

ntohl takes a uint32_t. I have messages with many different members (of type uint32_t or uint16_t). Is it possible to properly pass in the entire received struct or union and have it converted to say uint32_t and then reinterpret_cast into my union or struct?

How I have been doing it is listing, line-by-line, each individual member of the union or struct and passing it to ntohl/s like this msg.member = ntohl(msg.member); but that is cumbersome!

The data structures are transferred in whole from a C# .NET application (Windows) to a Linux application.

When I tried,

void* ptr = &msg;
uint32_t temp = (uint32_t)ptr;

The compiler complains that:

error: cast from 'void*' to 'uint32_t' loses precision

2

There are 2 answers

0
Tio Pepe On BEST ANSWER

No, you can't. Only in the case that your struct only contains one uint32_t variable. Besides, you must use different ntoh<X> functions depending the different variables sizes.

3
npclaudiu On

You can use Google's Protocol Buffers.