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的函數實現同上