我正在寻找一个(工作)示例,用于外部序列化 DLL 中的类结构。目前我找不到任何例子。Boost 文档只是说明了一些宏,论坛和新闻组只是在讨论其解决方案的具体问题。
所以我要求一个(外部)序列化类结构的示例,如下所示。除了类代码,我还添加了一些用于序列化的代码(这不起作用,请参阅底部的错误消息)。
class Foo
{
public:
Foo() { number_ = 0; }
virtual ~Foo() {}
int getNumber() { return number_; }
void setNumber( int var ) { number_ = var; }
private:
int number_;
};
class Bar : public Foo
{
public:
Bar() { doubleNumber_ = 0.0; }
virtual ~Bar() {}
double getDouble() { return doubleNumber_; }
void setDouble( double var ) { doubleNumber_ = var; }
private:
double doubleNumber_;
};
到目前为止,我所拥有的都是这样的代码:
序列化Foo.h
#ifndef _SERIALIZE_FOO_H_
#define _SERIALIZE_FOO_H_
#include "Foo.h"
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/version.hpp>
namespace boost {
namespace serialization {
template <typename Archive>
void save(Archive& ar, const Foo& object, const unsigned int version)
{
ar << object.getNumber();
}
template <typename Archive>
void load(Archive& ar, Foo& object, const unsigned int version)
{
int number;
ar >> number;
object.setNumber(number);
}
}} //namespace brackets
BOOST_SERIALIZATION_SPLIT_FREE( Foo )
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT_KEY( Foo )
#endif //_SERIALIZE_FOO_H_
序列化Foo.cpp
#include "serializeFoo.h"
BOOST_CLASS_EXPORT_IMPLEMENT( Foo )
序列化吧.h:
#ifndef _SERIALIZE_BAR_H_
#define _SERIALIZE_BAR_H_
#include "Bar.h"
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/version.hpp>
namespace boost {
namespace serialization {
template <typename Archive>
void save(Archive& ar, const Bar& object, const unsigned int version)
{
ar << base_object<Foo>(object);
ar << object.getDouble();
}
template <typename Archive>
void load(Archive& ar, Bar& object, const unsigned int version)
{
double doubleNumber;
ar >> doubleNumber;
object.setDouble(doubleNumber);
}
}} //namespace brackets
BOOST_SERIALIZATION_SPLIT_FREE( Bar )
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
BOOST_CLASS_EXPORT_KEY( Bar )
#endif //_SERIALIZE_BAR_H_
序列化吧.cpp:
#include "serializeBar.h"
BOOST_CLASS_EXPORT_IMPLEMENT( Bar )
序列化代码进入 DLL 并应在另一个使用类 Foo 和 Bar 的项目中使用。一切编译正常,但在运行时我收到消息
unregistered class - derived class not registered or exported
那么我是否使用了错误的宏?我错过了一个宏吗?上面的代码是正确的还是存在某种结构错误?也许这对很多其他人也很有用,我不认为将类的序列化放入 DLL 是非常奇特的......