我有以下结构:
typedef struct{
int test;
std::string name;
} test_struct;
然后,我在主函数中有如下代码:
int main(int argc, char *argv[]){
test_struct tstruct;
tstruct.test = 1;
tstruct.name = "asdfasdf";
char *testout;
int len;
testout = new char[sizeof(test_struct)];
memcpy(testout, &tstruct, sizeof(test_struct) );
std::cout<< testout;
}
但是,没有打印任何内容。怎么了?
最佳答案
sizeof(std::string) 产生相同的值 always .它不会为您提供字符串的运行时长度。要使用 memcpy 进行序列化,要么更改结构以包含 char 数组,例如 char buffer[20]
,要么通过在结构上定义一个方法来计算所需序列化缓冲区的大小,该方法给出了字节。
如果你想使用像 std::string 这样的成员,你需要遍历结构的每个成员并序列化。
memcpy(testout, (void *)&tstruct.test, sizeof(int) );
memcpy(testout+sizeof(int), tstruct.name.c_str(),tstruct.name.length() );
针对整个结构的 memcpy 在这种情况下将不起作用。
关于c++ - C++ 中的简单序列化示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23123583/