【发布时间】:2021-05-26 07:24:21
【问题描述】:
我正在尝试使用 UDP 通过 boost::asio 套接字发送作为派生类实例的对象。
假设子类是 PacketA,基类是 Packet。
我可以在客户端程序中对 PacketA 进行序列化,但是每当我尝试在服务器中对其进行反序列化时,它都会引发以下错误:
在抛出 'boost::archive::archive_exception' 的实例后调用终止 what(): 未注册的类
为了尝试解决这个问题,我在 PacketA cpp 文件中添加了宏 BOOST_CLASS_EXPORT_IMPLEMENT,在头文件中添加了 BOOST_CLASS_EXPORT_KEY,而在 Packet 类中我没有添加任何宏,但它仍然不起作用。由于boost docs 的这一部分,我添加了这些宏。
我也尝试使用register_type() 函数来注册子类,但我也没有成功,而且解决方案似乎比宏更糟糕。
我是否犯了任何明显的错误,或者我是否错误地使用了 API?
代码:
反序列化:
udp::endpoint senderEndPoint;
char buffer[MAX_PACKET_SIZE] = {"\n"};
int bytes = socket->receive_from(boost::asio::buffer(buffer, MAX_PACKET_SIZE), senderEndPoint, 0,error);
std::stringstream stringStream(buffer);
boost::archive::text_iarchive ia{stringStream};
Packet *packet; //<-It throws the exception in this line but If I switch this pointer to
//PacketA it works fine but the idea is to deserialize multiple child
//packets that came from the sockets.
ia & packet;
packet->bytes = 0;
packet->senderEndPoint = senderEndPoint;
数据包.cpp:
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include "Packet.hpp"
template<class Archive>
void Packet::serialize(Archive &ar, unsigned int version) {
//I didnt add any code in here since I don't really need to serialize any information just the child packets
}
template void Packet::serialize(boost::archive::text_iarchive &arch, const unsigned int version);
template void Packet::serialize(boost::archive::text_oarchive &arch, const unsigned int version);
数据包.hpp:
#include <boost/serialization/access.hpp>
#include <boost/serialization/export.hpp>
#include <boost/asio/ip/udp.hpp>
using PacketType = std::string;
class Packet {
public:
friend class boost::serialization::access;
/*Some variables and functions from packet*/
template<class Archive>
void serialize(Archive &, unsigned int version);
};
PacketA.cpp:
#include "PacketA.hpp"
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/base_object.hpp>
/*Some other functions*/
template<class Archive>
void PacketA::serialize(Archive &ar, unsigned int version) {
ar & boost::serialization::base_object<Packet>(*this);
ar & boost::serialization::make_nvp("PacketType", packetType);
}
BOOST_CLASS_EXPORT_IMPLEMENT(PacketA)
PacketA.hpp:
#include <boost/serialization/export.hpp>
#include "../Packet.hpp"
class PacketA : public Packet {
public:
PacketType packetType = "PacketA";
friend class boost::serialization::access;
/*Some functions*/
template<class Archive>
void serialize(Archive &ar, unsigned int version);
};
BOOST_CLASS_EXPORT_KEY(PacketA)
要序列化我正在使用此功能的所有数据包:
std::stringstream foo::serializePacket(Packet *packet) { //<-Here the *packet could be any
//packet child
std::stringstream ss;
boost::archive::text_oarchive oa{ss};
oa & packet;
return ss;
}
【问题讨论】:
标签: c++ serialization boost boost-asio