我正在尝试做的事情,利用 gSOAP:
请注意,此时我没有使用 Web 服务,我只对 XML 数据绑定(bind)感兴趣。
如果我的类(class)是这样的:
类基础{ ...
Der1 类:公共(public)基础{ ..
Der2 类:公共(public)基础{ ...
然后我可以使用以下方法序列化一个 Base 对象(它实际上可能是派生类型之一):
std::ofstream myFile;
myFile.open("output.out");
ctx.os = &myFile;
Der1 obj; // or Der2 obj...
// ... populate obj
if (soap_write_Base(ctx, dynamic_cast<Base*>(&obj)) == SOAP_OK)
{
std::cout << "message serialized" << std::endl;
} else
{
soap_print_fault(ctx, stderr);
}
反序列化使用:
std::ifstream myFile;
myFile.open("output.out");
ctx.is = &myFile;
Der1 obj;
if (soap_read_Der1(ctx, &obj) == SOAP_OK)
{
std::cout << "message deserialized" << std::endl;
printMessage(msg); //debug
} else
{
soap_print_fault(ctx, stderr);
}
其中 ctx 是指向 soap 上下文的指针,声明为:
soap* ctx = soap_new2(SOAP_XML_STRICT, SOAP_XML_INDENT);
在代码的其他地方。
谁能告诉我如何更改上面的反序列化代码,以便能够读取一个对象而无需预先知道它是 Der1、Der2 还是 Base 对象?
谢谢!
最佳答案
您需要做几件事。
首先,构建您的 C++ 对象,使它们派生自 xsd__anyType (-p 上的 wsdl2h 选项)
编译代码时,定义WITH_NO_IO和 WITH_NO_HTTP所以您不会获得默认的 gSoap HTTP 和 IO 调用。
然后,创建一个 Serializer像这样的类(请原谅关于 XML 的咆哮):
#pragma once
#include <memory>
namespace MyLib
{
class SerializerImpl;
class xsd__anyType;
class Serializer
{
std::shared_ptr<SerializerImpl> ser;
public:
Serializer();
Serializer(Serializer const &) = default;
Serializer(Serializer &&o) : ser(std::forward<Serializer>(o).ser) { }
~Serializer() = default;
Serializer &operator=(Serializer const& rhs) = default;
Serializer &operator=(Serializer && rhs)
{
ser = std::forward<Serializer>(rhs).ser;
return *this;
}
// Serialize 'value' into 'out'.
void Serialize(xsd__anyType const &value, std::ostream &out);
// Returns a shared pointer to the xsd_anyType that comes in 'in'.
// The shared_ptr returned contains a custom deleter because gSoap ties
// allocated values to the gSoap context used to deserialize it in the
// first place. I think that was an attempt at adding some kind of
// garbage collection so one didn't have to worry about deleting it except,
// of course, that fails if you get rid of the context prior to the
// end of the life of the deserialized value. Nobody does XML C++ bindings
// right. XML sucks and C++ doesn't and it is hard to translate suck to
// non-suck.
std::shared_ptr<xsd__anyType> Deserialize(std::istream &in);
};
}
实现看起来像:
#include "MyLibH.h"
#include "stdsoap2.h"
#include "Serializer.h"
namespace MyLib
{
static int fsend(struct soap* ctx, char const *buf, size_t len)
{
if (!ctx->os)
{
throw std::logic_error("soap.fsend the struct soap 'os' member must be set.");
}
ctx->os->write(buf, len);
return SOAP_OK;
}
static size_t frecv(struct soap* ctx, char* buf, size_t len)
{
if (!ctx->is)
{
throw std::logic_error("soap.fsend the struct soap 'is' member must be set.");
}
ctx->is->read(buf, len);
return ctx->is->gcount();
}
static SOAP_SOCKET fopen(struct soap*, const char*, const char*, int)
{
throw std::logic_error("soap.fopen not implemented for Serializer.");
}
static int fclose(struct soap *ctx)
{
return SOAP_OK;
}
static int fclosesocket(struct soap*, SOAP_SOCKET)
{
throw std::logic_error("soap.fclosesocket not implemented for Serializer.");
}
static int fshutdownsocket(struct soap*, SOAP_SOCKET, int)
{
throw std::logic_error("soap.fshutdownsocket not implemented for Serializer.");
}
static SOAP_SOCKET faccept(struct soap*, SOAP_SOCKET, struct sockaddr*, int *n)
{
throw std::logic_error("soap.faccept not implemented for Serializer.");
}
class SerializerImpl
{
struct soap mutable soap;
public:
SerializerImpl();
~SerializerImpl();
struct soap *ctx() const { return &soap; }
};
SerializerImpl::SerializerImpl()
{
soap_init(&soap);
// compiled with WITH_NOIO so set these function pointers
soap.fsend = fsend;
soap.frecv = frecv;
soap.fopen = fopen;
soap.fclose = fclose;
soap.fclosesocket = fclosesocket;
soap.fshutdownsocket = fshutdownsocket;
soap.fpoll = nullptr;
soap.faccept = faccept;
// Set input/output mode
soap_imode(&soap, SOAP_ENC_XML);
soap_set_omode(&soap, SOAP_XML_INDENT);
}
SerializerImpl::~SerializerImpl()
{
// remove deserialized class instances (C++ objects)
soap_destroy(&soap);
// clean up and remove deserialized data
soap_end(&soap);
// detach context (last use and no longer in scope)
soap_done(&soap);
}
Serializer::Serializer() : ser(std::make_shared<SerializerImpl>())
{
}
void Serializer::Serialize(xsd__anyType const& value, std::ostream &out)
{
soap_begin(ser->ctx());
ser->ctx()->is = ∈
soap_free_temp(ser->ctx());
int type;
int err;
char errbuf[200];
if ((err = soap_begin_recv(ser->ctx())) != SOAP_OK)
{
_snprintf_s(
errbuf,
sizeof(errbuf),
_TRUNCATE,
"Serializer::Deserialize failed soap_begin_recv: %d",
err);
errbuf[sizeof(errbuf) - 1] = 0;
throw std::exception(errbuf);
}
// Create a deleter for the element returned from 'soap_getelement()'
auto serializerImpl = this->ser;
auto deleteElement = [serializerImpl](void *toDelete)
{
soap_dealloc(serializerImpl->ctx(), toDelete);
};
// parse the XML into an element
std::unique_ptr<void, decltype(deleteElement)>
res(soap_getelement(ser->ctx(), &type), deleteElement);
if (!res)
{
// populate ser->ctx()->msgbuf with more detailed information
soap_set_fault(ser->ctx());
if (ser->ctx()->msgbuf)
{
_snprintf_s(
errbuf,
sizeof(errbuf),
_TRUNCATE,
"Serializer::Deserialize failed soap_getelement: %s",
ser->ctx()->msgbuf);
}
else
{
_snprintf_s(
errbuf,
sizeof(errbuf),
_TRUNCATE,
"Serializer::Deserialize failed soap_getelement: %d",
ser->ctx()->error);
}
errbuf[sizeof(errbuf) - 1] = 0;
throw std::exception(errbuf);
}
if ((err = soap_end_recv(ser->ctx())) != SOAP_OK)
{
_snprintf_s(
errbuf,
sizeof(errbuf),
_TRUNCATE,
"Serializer::Deserialize failed soap_end_recv: %d",
err);
errbuf[sizeof(errbuf) - 1] = 0;
throw std::exception(errbuf);
}
// anything that can be cast as an xml_Any gets cast here
switch (type)
{
case SOAP_TYPE_MyLib_ns1__FooType:
case SOAP_TYPE_MyLib_ns1__BarType:
case SOAP_TYPE_MyLib_ns1__BazType:
// In theory, res is a subclass of xsd_anyType, so cast
// it here as if it was
auto anyType = static_cast<xsd__anyType *>(res.release());
// build a shared pointer with the custom deleter that keeps serializerImpl
auto ret = std::shared_ptr<xsd__anyType>(anyType, deleteElement);
return ret;
}
_snprintf_s(
errbuf,
sizeof(errbuf),
_TRUNCATE,
"Serializer::Deserialize failed - "
"unsupported cast of type %d to xsd__anyType",
type);
errbuf[sizeof(errbuf) - 1] = 0;
throw std::exception(errbuf);
}
}
使用这个类,你可以创建一个 Serializer ser;然后做 ser.Serialize(myEntity, myOutputStream);或 auto myEntity = ser.Deserialize(myInputStream); .
您可以在 Deserialize() 中看到多态反序列化的 secret 。它调用 soap_getelement() 的方法它为它可以反序列化的任何类型返回一个空指针。然后,如果该类型是已知基于 xsd__anyType 的类型, 然后它被转换成 shared_ptr<xsd__anyType>使用保留在 struct soap 上的自定义删除方法上下文,以便它可以以适当的 gSoap 方式删除。转换到xsd__anyType的能力是我们告诉wsdl2h的原因使用 -p 从该类型派生我们所有的类型选项。
请注意,为了让它为我工作,我必须创建一些其他功能。 我使用 wsdl2h 构建源代码的方式和 soapcpp2 , WITH_NOGLOBAL得到定义。这导致了一些未定义的功能。我是这样定义的:
#include "MyLib3.nsmap"
SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultcode(struct soap *soap)
{
static char const *ret;
ret = nullptr;
return &ret;
}
SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultsubcode(struct soap *soap)
{
static char const *ret;
ret = nullptr;
return &ret;
}
SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultstring(struct soap *soap)
{
static char const *ret;
ret = nullptr;
return &ret;
}
SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultdetail(struct soap *soap)
{
static char const *ret;
ret = nullptr;
return &ret;
}
SOAP_FMAC3 const char * SOAP_FMAC4 soap_check_faultsubcode(struct soap *soap)
{
return nullptr;
}
SOAP_FMAC3 const char * SOAP_FMAC4 soap_check_faultdetail(struct soap *soap)
{
return nullptr;
}
SOAP_FMAC3 void SOAP_FMAC4 soap_serializefault(struct soap *soap)
{
}
SOAP_FMAC3 void SOAP_FMAC4 soap_serializeheader(struct soap *soap)
{
}
SOAP_FMAC3 int SOAP_FMAC4 soap_putheader(struct soap *soap)
{
return SOAP_OK;
}
SOAP_FMAC3 int SOAP_FMAC4 soap_getfault(struct soap *soap)
{
return SOAP_OK;
}
SOAP_FMAC3 int SOAP_FMAC4 soap_putfault(struct soap *soap)
{
return SOAP_OK;
}
SOAP_FMAC3 int SOAP_FMAC4 soap_getheader(struct soap *soap)
{
return SOAP_OK;
}
关于c++ - 如何在 gSOAP 中绑定(bind)多态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13822197/
出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)