× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Serialization of binary data in C and C++

<p><span style="font-size:18px">1. Always remember about fixed-size data types!</span><br> </p><pre><code class="language-cpp">// wrong struct Wrong { int a; unsigned short b; }; // correct struct Correct { int8_t a; uint16_t b; };</code></pre><p><br>2. Always remember about possible padding in structures!<br> </p><pre><code class="language-cpp">// Dangerous - might get additional padding at the end struct S { int8_t a; int16_t b; }; // Solution a struct Correct { int8_t a; int16_t b; int8_t _dummy; // manual padding to 32-bit }; // Solution b (Microsoft Compiler) #pragma pack(push, 1) struct Correct2 { int8_t a; int16_t b; }; #pragma pack(pop) // Solution c // Use C++11 alignas keyword</code></pre><p>3. Wrap dangerous parts in safe functions (C++ only)</p><pre><code>// Dangerous API int read(char* dst, int maxSize); int write(const char* src, int size); // Safe API struct MyData; MyData read() { MyData d; auto sz = read(reinterpret_cast&lt;char*&gt;(&amp;d), sizeof(d)); if (sz != sizeof(d)) { throw std::runtime_error("Reading failed!"); } return d; } void write(MyData const&amp; d) { auto sz = write(reinterpret_cast&lt;const char*&gt;(&amp;d), sizeof(d)); if (sz != sizeof(d)) { throw std::runtime_error("Writing failed!"); } }</code></pre><p> </p>
comments powered by Disqus