用ct.Pointer腌制ctypes.Structure

时间:2018-04-06 14:13:38

标签: python pickle ctypes

我有ctypes结构的以下类。

import ctypes as ct

class my_array(ct.Structure):
    _fields_ = [("_data", ct.POINTER(ct.c_uint32)),
                ("_size", ct.c_size_t)]

    def __init__(self, data):
        self._data = (ct.c_uint32 * len(data))()
        for i in range(0, len(data)):
            self._data[i] = data[i]
            self._size = len(data)

    def __reduce__(self):
        data = [None]*self._size
        for j in xrange(0, self._size):
            data[j] = self._data[j]
        return (my_array, (data,))


class my_struct(ct.Structure):
    _fields_ = [("numbs", my_array)]

但是,当我挑选第二个物体时

import cPickle
a = my_array([1, 2, 10])
b = my_struct(a)

with open('myfile', 'wb') as f:
    cPickle.dump(a, f)  # This succeeds
    cPickle.dump(b, f)  # This fails

我得到了例外

Traceback (most recent call last):
  File "tmp.py", line 30, in <module>
    cPickle.dump(a, f)  # This fails
ValueError: ctypes objects containing pointers cannot be pickled

自从__reduce__中实施my_array以来,我不明白为什么会发生这种情况?实施__getstate__也不起作用。

我知道我可以在__reduce__中再次重载my_struct但这对我来说似乎过于复杂,因为每次我在结构中包含__reduce__时我都要保持重载my_array

0 个答案:

没有答案