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

标签 python c serialization ctypes dynamic-arrays

我最近继承了一个项目,我们反序列化了我无法更改的系统写出的一堆数据(希望他们使用标准序列化器,但我无法更改它)。在大多数情况下,我能够使用 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;
}

我们将不胜感激!

最佳答案

您是否尝试查看 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:])

关于python - 在 Python 中使用动态数组反序列化 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44577938/

相关文章:

python - 为什么是一个包罗万象的尝试 :/except: not enough to catch an exception?

c - 如何使用文件中的数据填充已分配的二维数组?

python - 使用数组条目存储数据框

python - 你如何检查 Python 字典中是否存在许多键?

python - Python 中的响应面建模和优化 : Analogous to rsm in R?

c - 是否可以将 16 位值与 8 位比较匹配 ISR 进行比较

java - Java 方法中序列化/反序列化子类对象

Java尝试创建一个类来将ArrayList打印到文件

javascript - 使用 AJAX 在 Flask 和 JS 之间发送数据以进行 chrome 扩展

c - 在运行 Ubuntu 19.10 的 x64 系统中,文件描述符的大小(以位为单位)是多少?