简体   繁体   English

C 相当于 python pickle(对象序列化)?

[英]C equivalent to python pickle (object serialization)?

What would be the C equivalent to this python code?与此 python 代码等效的 C 是什么? Thanks.谢谢。

data = gather_me_some_data()
# where data = [ (metic, datapoints), ... ]
# and datapoints = [ (timestamp, value), ... ]

serialized_data = cPickle.dumps(data, protocol=-1)
length_prefix = struct.pack("!L", len(serialized_data))
message = length_prefix + serialized_data

C doesn't supports direct serialization mechanism because in C you can't get type information at run-time. C 不支持直接序列化机制,因为在 C 中你无法在运行时获取类型信息。 You must yourself inject some type info at run-time and then construct required object by that type info.您必须自己在运行时注入一些类型信息,然后通过该类型信息构造所需的 object。 So define all your possible structs:所以定义所有可能的结构:

typedef struct {
  int myInt;
  float myFloat;
  unsigned char myData[MY_DATA_SIZE];
} MyStruct_1;

typedef struct {
  unsigned char myUnsignedChar;
  double myDouble;
} MyStruct_2;

Then define enum which collects info about what structs in total you have:然后定义枚举,它收集有关您总共拥有的结构的信息:

typedef enum {
  ST_MYSTRUCT_1,
  ST_MYSTRUCT_2
} MyStructType;

Define helper function which lets to determine any struct size:定义 helper function 它可以确定任何结构大小:

int GetStructSize(MyStructType structType) {
      switch (structType) {
          case ST_MYSTRUCT_1:
              return sizeof(MyStruct_1);
          case ST_MYSTRUCT_2:
              return sizeof(MyStruct_2);
          default:
              // OOPS no such struct in our pocket
              return 0;
      }
}

Then define serialize function:然后定义序列化function:

void BinarySerialize(
    MyStructType structType,
    void * structPointer,
    unsigned char * serializedData) {

  int structSize = GetStructSize(structType);

  if (structSize != 0) {
    // copy struct metadata to serialized bytes
    memcpy(serializedData, &structType, sizeof(structType));
    // copy struct itself
    memcpy(serializedData+sizeof(structType), structPointer, structSize);
  }
}

And de-serialization function:反序列化function:

void BinaryDeserialize(
    MyStructType structTypeDestination,
    void ** structPointer,
    unsigned char * serializedData)
{
    // get source struct type
    MyStructType structTypeSource;
    memcpy(&structTypeSource, serializedData, sizeof(structTypeSource));

    // get source struct size
    int structSize = GetStructSize(structTypeSource);

    if (structTypeSource == structTypeDestination && structSize != 0) {
      *structPointer = malloc(structSize);
      memcpy(*structPointer, serializedData+sizeof(structTypeSource), structSize);
    }
}

Serialization usage example:序列化使用示例:

MyStruct_2 structInput = {0x69, 0.1};
MyStruct_1 * structOutput_1 = NULL;
MyStruct_2 * structOutput_2 = NULL;
unsigned char testSerializedData[SERIALIZED_DATA_MAX_SIZE] = {0};

// serialize structInput
BinarySerialize(ST_MYSTRUCT_2, &structInput, testSerializedData);
// try to de-serialize to something
BinaryDeserialize(ST_MYSTRUCT_1, &structOutput_1, testSerializedData);
BinaryDeserialize(ST_MYSTRUCT_2, &structOutput_2, testSerializedData);
// determine which object was de-serialized
// (plus you will get code-completion support about object members from IDE)
if (structOutput_1 != NULL) {
   // do something with structOutput_1 
   free(structOutput_1);
}
else if (structOutput_2 != NULL) {
   // do something with structOutput_2
   free(structOutput_2);
}

I think this is most simple serialization approach in C. But it has some problems:我认为这是 C 中最简单的序列化方法。但它存在一些问题:

  • struct must not have pointers, because you will never know how much memory one needs to allocate when serializing pointers and from where/how to serialize data into pointers. struct 不能有指针,因为你永远不会知道在序列化指针时需要分配多少 memory 以及从何处/如何将数据序列化为指针。
  • this example has issues with system endianess - you need to be careful about how data is stored in memory - in big-endian or little-endian fashion and reverse bytes if needed [when casting char * to integal type such as enum ] (...or refactor code to be more portable).此示例存在系统字节序问题 - 您需要注意数据如何存储在 memory 中 - 以大端或小端方式存储,并在需要时反转字节 [当将char *转换为整数类型(如enum )时] (.. .or 重构代码以使其更具可移植性)。

If you can use C++, there is the PicklingTools library如果你可以使用 C++,有 PicklingTools

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM