|
| 1 | +// C++ headers |
| 2 | +#include <iomanip> |
| 3 | +#include <ios> |
| 4 | +#include <iostream> |
| 5 | +#include <vector> |
| 6 | + |
| 7 | +// ROOT headers |
| 8 | +#include <TBufferFile.h> |
| 9 | +#include <TClass.h> |
| 10 | + |
| 11 | +template <typename T> |
| 12 | +void print_vector(std::vector<T> const& v) { |
| 13 | + if (v.empty()) { |
| 14 | + std::cout << "{}"; |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + std::cout << "{ " << v[0]; |
| 19 | + for (unsigned int i = 1; i < v.size(); ++i) { |
| 20 | + std::cout << ", " << v[i]; |
| 21 | + } |
| 22 | + std::cout << " }"; |
| 23 | +} |
| 24 | + |
| 25 | +void print_buffer(const char* buffer, int size) { |
| 26 | + auto flags = std::cout.flags(); |
| 27 | + for (int i = 0; i < size; ++i) { |
| 28 | + if (i % 16 == 0) |
| 29 | + std::cout << '\t'; |
| 30 | + unsigned char value = buffer[i]; |
| 31 | + std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)value; |
| 32 | + std::cout << ((i % 16 == 15 or i == size - 1) ? '\n' : ' '); |
| 33 | + } |
| 34 | + std::cout.flags(flags); |
| 35 | +} |
| 36 | + |
| 37 | +int main() { |
| 38 | + // Type of the object to serialise and deserialise |
| 39 | + using Type = std::vector<float>; |
| 40 | + |
| 41 | + // Original vector to serialize |
| 42 | + Type send_object = {1.1, 2.2, 3.3, 4.4, 5.5}; |
| 43 | + |
| 44 | + // Display the contents of the original vector |
| 45 | + std::cout << "Original object: "; |
| 46 | + print_vector(send_object); |
| 47 | + std::cout << "\n"; |
| 48 | + |
| 49 | + // Create a buffer for serialization |
| 50 | + TBufferFile send_buffer(TBuffer::kWrite); |
| 51 | + |
| 52 | + // Get the TClass for the type to serialise |
| 53 | + //TClass* type = TClass::GetClass<Type>(); |
| 54 | + TClass* type = TClass::GetClass(typeid(Type)); |
| 55 | + |
| 56 | + // Serialize the vector into the buffer |
| 57 | + send_buffer.WriteObjectAny((void*)&send_object, type, false); |
| 58 | + int size = send_buffer.Length(); |
| 59 | + |
| 60 | + // Display the contents of the buffer |
| 61 | + std::cout << "Serialised object is " << size << " bytes long:\n"; |
| 62 | + print_buffer(send_buffer.Buffer(), size); |
| 63 | + |
| 64 | + // Create a new buffer for deserialization |
| 65 | + TBufferFile recv_buffer(TBuffer::kRead, size); |
| 66 | + |
| 67 | + // Copy the buffer |
| 68 | + std::memcpy(recv_buffer.Buffer(), send_buffer.Buffer(), size); |
| 69 | + |
| 70 | + // Deserialize into a new vector |
| 71 | + std::unique_ptr<Type> recv_object{reinterpret_cast<Type*>(recv_buffer.ReadObjectAny(type))}; |
| 72 | + |
| 73 | + // Display the contents of the new vector |
| 74 | + std::cout << "Deserialized object: "; |
| 75 | + print_vector(*recv_object); |
| 76 | + std::cout << "\n"; |
| 77 | + |
| 78 | + return 0; |
| 79 | +} |
0 commit comments