SPDataPickle: c语言的结构体和 xml/json/protobuf 的自动转化

SPDataPickle 是一种轻便高效的结构化数据和xml/json/protobuf自动序列化库,很适合 RPC 数据交换的场合。

[url]http://code.google.com/p/spdatapickle[/url]
[url]http://spdatapickle.googlecode.com/files/spdatapickle-0.5.src.tar.gz[/url]

大家可能对 google 的 protocol buffers 都早有耳闻。SPDataPickle 和 protobuf 很相似。

仿照 google protobuf 的例子,也来一个 Person 的简单例子。

对应 a.proto ,要写一个 a.xml
[code]
<metainfo prefix="XYZ" filename="account">
<struct name="Person">
<field name="id" type="int32" />
<field name="name" type="*char" />
<field name="email" type="*char" />
</struct>
</metainfo>
[/code]

然后使用 spxml2struct 处理这个 a.xml,生成具体的 structure 定义和 metainfo 。
[code]
enum {
eTypeXYZPerson = eTypeSPDPUserDefine + 1
};

typedef struct tagXYZPerson {
int mId;
char * mName;
char * mEmail;
} XYZPerson_t;

typedef struct tagSP_DPMetaInfo SP_DPMetaInfo_t;
extern SP_DPMetaInfo_t * gXYZAccountMetaInfo;
[/code]

然后就可以对这个 XYZPerson_t 结构进行序列化和反序列化。
[code]
int main( int argc, char * argv[] )
{
XYZPerson_t person;

person.mId = 123;
person.mName = strdup( "Bob" );
person.mEmail = strdup( "bob@example.com" );

SP_XmlStringBuffer buffer;

SP_XmlPickle pickle( gXYZAccountMetaInfo );
pickle.pickle( &person, sizeof( person ), eTypeXYZPerson, &buffer );

printf( "xml: %s\n", buffer.getBuffer() );

XYZPerson_t other;
pickle.unpickle( buffer.getBuffer(), buffer.getSize(),
eTypeXYZPerson, &other, sizeof( other ) );

printf( "id %d, name %s, email %s\n", other.mId, other.mName, other.mEmail );

SP_DPAlloc alloc( gXYZAccountMetaInfo );

alloc.free( &person, sizeof( person ), eTypeXYZPerson );
alloc.free( &other, sizeof( person ), eTypeXYZPerson );

return 0;
}
[/code]

输出结果
[code]
xml: <Person>
<id>123</id>
<name>Bob</name>
<email>bob@example.com</email>
</Person>

id 123, name Bob, email bob@example.com
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值