python - 使用 numpy.frombuffer 读取 cffi.buffer 时如何处理 C 结构中的成员填充?

标签 python c numpy struct python-cffi

我必须读取从 dll 返回的 C 结构数组并将其转换为 Numpy 数组。该代码使用 Python 的 cffi 模块。

代码到目前为止有效,但我不知道如何处理 np.frombuffer 提示的结构中的成员填充:

ValueError: buffer size must be a multiple of element size

这是我的代码:

from cffi import FFI
import numpy as np

s = '''
    typedef struct
    {
        int a;
        int b;
        float c;
        double d;
    } mystruct;
    '''

ffi = FFI()
ffi.cdef(s)

res = []

#create array and fill with dummy data
for k in range(2):

    m = ffi.new("mystruct *")

    m.a = k
    m.b = k + 1
    m.c = k + 2.0
    m.d = k + 3.0

res.append(m[0])

m_arr = ffi.new("mystruct[]", res)

print(m_arr)

# dtype for structured array in Numpy
dt = [('a', 'i4'),
      ('b', 'i4'),
      ('c', 'f4'),
      ('d', 'f8')]

# member size, 20 bytes
print('size, manually', 4 + 4 + 4 + 8)

# total size of struct, 24 bytes
print('sizeof', ffi.sizeof(m_arr[0]))

#reason is member padding in structs

buf = ffi.buffer(m_arr)
print(buf)

x = np.frombuffer(buf, dtype=dt)
print(x)

有什么想法可以干净地处理这个问题吗?


编辑:

如果我在应该发生填充的 dtype 中添加一个额外的数字,它似乎可以工作:

dt = [('a', 'i4'),
      ('b', 'i4'),
      ('c', 'f4'),
      ('pad', 'f4'),
      ('d', 'f8')]

为什么填充发生在那里? (Win7,64 位,Python 3.4 64 位)。

但这不是最好的方法。真正的代码要复杂得多而且动态多,所以应该可以以某种方式处理这个问题,对吗?

最佳答案

可能最方便的方法是在 numpy dtype constructor 中使用关键字 align=True .这将自动进行填充。

dt = [('a', 'i4'),
      ('b', 'i4'),
      ('c', 'f4'),
      ('d', 'f8')]

dt_obj = np.dtype(dt, align=True)
x = np.frombuffer(buf, dtype=dt_obj)

(另见关于结构化数组的 Numpy doc)

关于python - 使用 numpy.frombuffer 读取 cffi.buffer 时如何处理 C 结构中的成员填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48423725/

相关文章:

python - Keras:ResourceExhaustedError(请参阅上面的回溯):分配具有形状的张量时出现 OOM [26671,32,32,64]

Python Tornado : Sending websocket messages from another class

c - 纪元(以秒为单位)到 C 中的 MJD 转换

c - 输入的动态内存分配?

python - Theano输入输出样本数错误

python - 如何将照片插入 Tkinter 窗口,没有 PIL 的枕头

c - 为什么模在此 C 代码中无法正常运行?

python - 使用 python(字节数组和 numpy)读取 middlebury 'flow' 文件

python - 使用 Python、Numpy 数组和 WAVE 模块编写 WAV 文件

python - MatLab 和 numpy 中 Hermitian 矩阵特征值的差异