在Python中用动态数组反序列化C结构

2024-04-26 07:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近继承了一个项目,在该项目中,我们反序列化了一组由系统写入的数据,但我无法更改这些数据(希望他们使用标准序列化程序,但我无法更改)。在大多数情况下,我能够使用ctypes来表示结构,并将数据直接转换到Python中,但是在某些情况下,底层的数据结构是一团糟的(同样,无论我做了多少尝试,我都无法更改)。当c结构定义如下时,有两种情况让我发疯,试图找到一种有效的方法:

简单案例:

struct b{
  int data;
  int more_data;
};

struct a{
  int num_entries;
  b* data;
}; 

当它被序列化时,它将b*数据打包到内存中,就像它是一个静态数组一样。你知道吗

我要处理的最可怕的案子来了:

struct c{
  int a;
  int b;
};

struct b{
  int random_data;
  c* data;
  int more_data;
};

struct a{
  int len; // This actually defines the length in struct b for "data" array size
  b nested_data;
  c why_not_it_is_this_poorly_organized;
}

任何帮助都将不胜感激!你知道吗


Tags: 数据项目程序数据结构data标准序列化系统
1条回答
网友
1楼 · 发布于 2024-04-26 07:23:49

你试过看Python bitstring API吗?从这里您可以编写一些方法,通过切片数组来反序列化数据。它可能看起来像这样:

def parse_c(buffer):
    # Parse data into list

def parse_b(buffer):
    # Parse first int of B
    list = parse_c(buffer[8:-8]) # skip first/last int
    # Parse last int of B

def parse_a(buffer):
    # Parse len (you could also pass this into parse_b, but b can figure it out from the size)
    b = parse_b(buffer[-8:-16])
    c = parse_c(buffer[-16:])

相关问题 更多 >