Home > Backend Development > C++ > body text

How to Serialize and Deserialize a C Class with Custom Data Types?

DDD
Release: 2024-10-30 05:39:03
Original
434 people have browsed it

How to Serialize and Deserialize a C   Class with Custom Data Types?

How to do serialization of Class having members of custom data types in C ?

Problem

The goal is to serialize and deserialize a C class Mango that contains members of custom data types.

Implementation

The suggested implementation includes the following functions:

<code class="cpp">std::vector<uint8_t> serialize(Mango const& Man);
Mango                deserialize(std::span<uint8_t const> data);

void serialize_to_stream(std::ostream& os, Mango const& Man);
void deserialize(std::istream& is, Mango& Man);</code>
Copy after login

Customizations for Data Types

Customizations are required for all relevant types (including ValType, FuntionMango, MangoType, and Mango):

<code class="cpp">// Define `do_generate` and `do_parse` functions
// for custom data types.</code>
Copy after login

Example Implementation

<code class="cpp">void serialize_to_stream(std::ostream& os, Mango const& Man) {
    do_generate(std::ostreambuf_iterator<char>(os), Man);
}

void deserialize(std::istream& is, Mango& Man) {
    Man = {}; // clear it!
    std::istreambuf_iterator<char> f(is), l{};
    if (!do_parse(f, l, Man))
        throw std::runtime_error("deserialize");
}</code>
Copy after login

Portability Considerations

  • Endianness may need to be normalized, which can be done manually or using a library like Boost Endian (header-only).

Additional Notes

  • This approach allows data to be efficiently stored and transferred between different processes or systems.

Live Example:

https://coliru.stacked-crooked.com/a/288829ec964a3ca9

The above is the detailed content of How to Serialize and Deserialize a C Class with Custom Data Types?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!