I am making a communication module between processes using boost::interprocess::message_queue
Because message queue takes array buffer, I would to serialize a packet into an array buffer.
inline void message_queue_t<VoidPointer>::send
(const void *buffer, size_type buffer_size, unsigned int priority)
for example,
header header(5, 2);
char buffer[64] = {};
uint32_t size = header.save(buffer);
queue.send(buffer, sizeof(size), 0); // queue is boost::interprocess::message_queue
Here's a progress:
#ifndef IPC_PACKET_HEADER_HPP
#define IPC_PACKET_HEADER_HPP
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/iostreams/stream.hpp>
#include <iostream>
#include <string>
class header {
public:
header(uint32_t id, uint32_t size) :
id_(id),
size_(size) {
}
~header() = default;
uint32_t save(char* buffer) {
boost::iostreams::basic_array_sink<char> sink((char *)buffer, 64);
boost::iostreams::stream<boost::iostreams::basic_array_sink<char>> os(sink);
boost::archive::binary_oarchive oa(os);
oa & *(this);
return 0; // size that are copied to the buffer?
}
void load(const void* data) {
// boost::archive::binary_iarchive ia(iss);
// ia & *(this);
}
private:
friend class boost::serialization::access;
uint32_t id_;
uint32_t size_;
template<class Archive>
void serialize(Archive& ar, const unsigned int version) {
ar & id_;
ar & size_;
}
};
#endif
Two questions.
- When serialized using save() function, I need to know the size that are serialized so that I can pass it to the send function of
boost::interprocess::message_queue. How do we get this size? - I am running out of idea how to make load function. It suppose to get a byte data and should load them itself. Can you help with this?
I would appreciate any inputs.
Dynamic Buffer
I would suggest using a dynamically sized container:
Now you will just have
buffer.size()reflecting the bytes serialized:Static Buffer
Of course, if you insist you can make use of a statically sized container.
Here, the returned value is the resulting seek position into the put buffer of the stream.
Loading
Regardless of the chosen approach, loading looks the same:
Live Demo
Demonstrating all the approaches and also optimizing archive size using some flags:
Live On Coliru
Prints the informative and expected:
BONUS
Since the Boost Serialization buys you no functionality here (no object tracking, object graph recursion, not even portability) consider just using bitwise serialization here:
Live On Coliru
Note how it doesn't use Boost Serialization, Boost Iostreams, or any boost at all, and the header serializes into 8 bytes intead of 53 using a serialization archive: