- 论坛徽章:
- 0
|
SPDataPickle 是一个用于在 C语言的结构体和 xml/json 之间做自动转化的库。
http://code.google.com/p/spdatapickle
http://spdatapickle.googlecode.c ... ckle-0.5.src.tar.gz
大家可能对 google 的 protocol buffers 都早有耳闻。SPDataPickle 和 protobuf 很相似。
仿照 google protobuf 的例子,也来一个 Person 的简单例子。
对应 a.proto ,要写一个 a.xml
- <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>
复制代码
然后使用 spxml2struct 处理这个 a.xml,生成具体的 structure 定义和 metainfo 。
- 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;
复制代码
然后就可以对这个 XYZPerson_t 结构进行序列化和反序列化。
- 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;
- }
复制代码
输出结果
- xml: <Person>
- <id>123</id>
- <name>Bob</name>
- <email>bob@example.com</email>
- </Person>
- id 123, name Bob, email [email]bob@example.com[/email]
复制代码
[ 本帖最后由 iunknown 于 2009-11-6 23:14 编辑 ] |
|