Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h3>Ideally use <code>memcpy(3)</code>, at least use type <code>_gamedata</code>, or define a protocol</h3> <p>We can consider two use cases. In what I might call the programmer-API type, serialization is an internal convenience and the record format is determined by the compiler and library. In the more formally defined and bulletproof implementation, a protocol is defined and a special-purpose library is written to portably read and write a stream.</p> <p>The best practice will differ depending on whether it makes sense to create a versioned protocol and develop stream I/O operations.</p> <h3>API</h3> <p>The best and most completely portable implementation when reading from compiler-oject serialized streams would be to declare or dynamically allocate an exact or max-sized <code>_gamedata</code> and then use <code>memcpy(3)</code> to pull the data out of the serial stream or device memory or whatever it is. This lets the compiler allocate the object that is accessed by compiler code and it lets the developer allocate the object that is accessed by developer (i.e., <code>char *</code>) logic.</p> <p>But at a minimum, set a pointer to <code>_gamedata</code> and the compiler will do everything for you. Note also that <code>res_table[n]</code> will always be at the "right" address regardless of the size of the <code>res_table[]</code> array. It's not like making it bigger changes the location of the first element.</p> <h3>General serialization best practice</h3> <p>If the <code>_gamedata</code> object itself is in a buffer and potentially misaligned, i,e., if it is anything other than an object allocated for a <code>_gamedata</code> type by the compiler or dynamically by a real allocator, then you still have potential alignment issues and the only correct solution is to <code>memcpy(3)</code> each discrete type out of the buffer. </p> <p>A typical error is to use the misaligned pointer anyway, because it works (slowly) on x86. But it may not work on mobile devices, or future architectures, or on some architectures when in kernel mode, or with advanced optimizations enabled. It's best to stick with real C99.</p> <h3>It's a protocol</h3> <p>Finally, when serializing binary data in any fashion you are really <em>defining a protocol</em>. So, for maximum robustness, don't let the compiler define your protocol. Since you are in C, you can generally handle each fundamental object discretely with no loss in speed. If both the writer and reader do it, then only the developers have to agree on the protocol, not the developers and the compilers and the build team, and the C99 authors, and Dennis M. Ritchie, and probably some others.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload