1

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

  • Th answer will be different for unions and structs depending on the number and types of their members. – Mooing Duck Oct 26 '11 at 14:54
  • 1
    The example won't work anyway, as you don't cast the struct into a `uint32_t` (which would only work if the struct contains a single `uint32_t` member), but the struct's address. So this will result in complete rubbish. What you wanted was `uint32_t temp = *(uint32_t*)&msg`, but like said this will only work if the struct has only a single member of type `uint32_t`. – Christian Rau Oct 26 '11 at 15:00
  • Can you modify the C# app to change how the data will be passed? – cHao Oct 26 '11 at 15:51

2 Answers2

6

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.

Tio Pepe
  • 3,071
  • 1
  • 17
  • 22
0

You can use Google's Protocol Buffers.

npclaudiu
  • 2,401
  • 1
  • 18
  • 19
  • 1
    Not seeing how this answers the question. Protocol buffers squish the data into a different format entirely, don't they? That being their job and all...you'll need a lot more than "use protocol buffers" in order for this to be a useful answer. Like, say, an example. – cHao Oct 26 '11 at 15:00
  • It does exactly what @0A0D needs: it handles serialization. Instead of manually writing and reading fields one by one, which can be cumbersome, you simply declare your structure in a .proto file and protoc generates (highly optimized) code that does just that. – npclaudiu Oct 26 '11 at 15:06
  • 1
    If he happens to be transferring the struct from an *existing* app, though, protocol buffers would mangle the data beyond recognition. He'd need to rewrite both sides to use protocol buffers instead of raw structs. And it hasn't been said yet whether he has the access or ability to do that. – cHao Oct 26 '11 at 15:47