CDR可以提供对基本数据类型如int,short,double,string等的序列化机制,简单包装后即可担当RPC中的序列化角色。
#include <iostream>
#include <string>
#include <ace/OS.h>
#include <ace/String_Base.h>
#include <ace/CDR_Stream.h>
using namespace std;
#pragma comment(lib,"aced")
int main(int argc, char* argv[])
{
cout << "ACE CDR demo" << endl;
ACE_CString sAppName = "CDRDemo",sAppName2;
ACE_CDR::Long nUID = 123456,nUID2;
ACE_CDR::Float nfPosX = 120.51,nfPosX2;
ACE_CDR::Double ndScore = 120.51,ndScore2;
ACE_CString sDummy = "another string",sDummy2;
ACE_CDR::Short nsLength = 10,nsLength2;
ACE_OutputCDR outCDR(ACE_DEFAULT_CDR_BUFSIZE);
outCDR << nUID;
outCDR << nfPosX;
outCDR << ndScore;
outCDR << sAppName;//写字符串时,先写入字符串的长度
outCDR << sDummy;
outCDR << nsLength;
cout << "OutputCDR size = " << outCDR.length() << endl;
//可以通过socket发送出去,而在服务端进行下面的解析
//1.ACE_Message_Block *ACE_OutputCDR::begin (void)
//2.通过ACE_SOCK_Stream发送出去
ACE_InputCDR inCDR(outCDR);
inCDR >> nUID2;
inCDR >> nfPosX2;
inCDR >> ndScore2;
inCDR >> sAppName2;
inCDR >> sDummy2;
inCDR >> nsLength2;
ACE_ASSERT(nUID == nUID2);
ACE_ASSERT(nfPosX == nfPosX2);
ACE_ASSERT(ndScore == ndScore2);
ACE_ASSERT(sAppName == sAppName2);
ACE_ASSERT(sDummy == sDummy2);
ACE_ASSERT(nsLength == nsLength2);
cout << "test ok." << endl;
return 0;
}
假若有如下的demo.idl,内容如下:
struct user_info
{
int user_id;
string user_name;
}
利用idl_gen生成代码时:
(1)如果是侵入式的方案,则生成user_info类时,自动添加成员OutputCDR和InputCDR成员,并添加pack(ACE_Message_Block &* msg)和parse(ACE_Message_Block * msg)成员函数,在pack和parse里面,调到对于的CDR类,按照类中数据成员的声明顺序依次序列化,反序列化
(2)如果是非侵入式方案,则生成user_info类时,生成独立函数的pack(user_info& info, ACE_Message_Block &* msg)和parse(user_info& info,ACE_Message_Block * msg),pack和parse的函数实现同上