我有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