Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It should be perfectly fine to do this:

  union reinterpret {
    char raw[100];
    struct myStruct interpreted;
  } example;

  read(fd, &example.raw)
  struct myStruct dest = interpreted;

This is standard-compliant C code, and it is a common way of reading IP addresses from packets, for example.


You don't even need to pun that. It's legal to say:

    struct myStruct example;
    read(fd, &example, sizeof(example));
That "should present no problem unless binary data written by one implementation are read by another" quoth ANSI X3.159-1988. One example of a time where I've used that, is when storing intermediary build artifacts. Those artifacts only exist on the host machine. If the binary that writes/reads those artifacts gets recompiled, then the Makefile will invalidate the artifacts so they're regenerated. Since flags like -mstructure-size-boundary=n do exist and ABI breakages have happened with structs in the past.


(It should be noted that this is not valid C++ code.)


Sensitive emotional subjects shouldn't be noted. Reminding C developers of the void* incompatibility is a good way to get them to feel triggered because it makes the language unpleasant.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: