使用TPL在结构中序列化wchar_t *

时间:2010-09-12 09:36:27

标签: c serialization unicode task-parallel-library

我正在尝试使用tpl来序列化包含wchar_t *字符串的结构。

我看到的代码看起来像是这样,而且它不起作用:

#include <stdio.h>
#include <locale.h>
#include <string.h>
#include <wchar.h>
#include "tpl.h"

struct chinese_t {
    wchar_t *chars;
};


int main() {

tpl_node *tn;


struct chinese_t cstr;
cstr.chars = L"字符串";

tn = tpl_map("S(s)", &cstr);
tpl_pack( tn, 0 );
tpl_dump(tn, TPL_FILE, "string.tpl");
tpl_free(tn);


struct chinese_t cstr2;

tn = tpl_map( "S(s)", &cstr2);
//tpl_load(tn, TPL_MEM, buffer, len);
tpl_load(tn, TPL_FILE, "string.tpl");
tpl_unpack(tn, 0);
tpl_free(tn);


printf("%ls\n", cstr2.chars);
return;
}

如果我用“1234”替换中文“字符串”字符串,它只打印“1” - 如果我更改定义以便struct使用char *(我只将ASCII字符插入其中)它可以工作正好。但是我无法弄清楚如何正确地序列化和反序列化wchar_t *字符串。

1 个答案:

答案 0 :(得分:2)

之前我没有使用过tpl,但是从文档的快速浏览来看,它似乎并不直接支持宽字符。您在字符串“1234”中看到的行为与包含字节“1 \ x002 \ x003 \ x004 \ x00 \ x00 \ x00”的UTF-16编码字符串一致,该字符串被tpl视为仅由NUL终止的字节字符串“1 \ x00”。

看起来你最好的选择可能是:

  • 将tpl中的宽字符串表示为16位整数数组;
  • 将您的字符串编码为UTF-8 char字符串并使用tpl字符串类型;或
  • 修改tpl以包含宽字符串类型。