Due to certain constraints I am forced to use a C float array for one of my libraries. The array is malloc'ed following some processing. How would I allocate memory within the serialize()
method?
If you move the malloc from init()
to the constructor, the code works.
#include <iostream>
#include <fstream>
#include <cstdlib>
#pragma warning(disable: 4244)
#include <boost/serialization/serialization.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
struct Monkey
{
int num = 256*70000;
float* arr;
Monkey()
{}
void init() {
arr = (float*)malloc(num*sizeof(float));//new float[num];
}
~Monkey() { free(arr); }
};
namespace boost
{
namespace serialization
{
template<class Archive>
void serialize(Archive & ar, Monkey& m, const unsigned int version)
{
ar & m.num;
ar & make_array<float>(m.arr, m.num);
}
}
}
int main(int argc, char* argv[])
{
const char* name = "monkey.txt";
{
Monkey m;
m.init();
std::ofstream outStream(name, std::ios::out | std::ios::binary | std::ios::trunc);
boost::archive::binary_oarchive oar(outStream);
oar << (m);
}
Monkey m;
std::ifstream inStream(name, std::ios::in | std::ios::binary);
boost::archive::binary_iarchive iar(inStream);
iar >> (m);
//std::copy(m.arr, m.arr + m.num, std::ostream_iterator<float>(std::cout, ";"));
std::cout << m.arr[10] << std::endl;
}
To be honest, I don't really get what's going on under the hood with boost serialization. It's just a black box to me. I'm too much of a beginner to read its source code.