我的当前方法是创建一个numpy数组,它提供了对ctypes指针的直接视图:
import numpy as np
import ctypes as C
libc = C.CDLL('libc.so.6')
class MyWrapper(object):
def __init__(self, n=10):
# buffer allocated by external library
addr = libc.malloc(C.sizeof(C.c_int) * n)
self._cbuf = (C.c_int * n).from_address(addr)
def __del__(self):
# buffer freed by external library
libc.free(C.addressof(self._cbuf))
self._cbuf = None
@property
def buffer(self):
return np.ctypeslib.as_array(self._cbuf)
除了避免复制外,这还意味着我可以使用numpy的索引和分配语法,并直接将其传递给其他numpy函数:
wrap = MyWrapper()
buf = wrap.buffer # buf is now a writeable view of a C-allocated buffer
buf[:] = np.arange(10) # this is pretty cool!
buf[::2] += 10
print(wrap.buffer)
# [10 1 12 3 14 5 16 7 18 9]
然而,它也具有固有的危险性:
del wrap # free the pointer
print(buf) # this is bad!
# [1852404336 1969367156 538978662 538976288 538976288 538976288
# 1752440867 1763734377 1633820787 8548]
# buf[0] = 99 # uncomment this line if you <3 segfaults
为了更安全,我需要能够检查底层的C指针是否已经被释放,然后再尝试读取/写入数组内容。我有一些关于如何实现这个目标的想法:
- 一种方法是生成
np.ndarray
的子类,该子类保存对MyWrapper
的_cbuf
属性的引用,在进行任何读取/写入其底层内存之前检查它是否为None
,如果是则抛出异常。 - 我可以轻松地生成多个视图到同一个缓冲区,例如通过
.view
转换或切片,因此每个视图都需要继承对_cbuf
的引用和执行检查的方法。我认为可以通过重写__array_finalize__
来实现这一点,但我不确定具体如何操作。 - "指针检查"方法还需要在任何读取和/或写入数组内容的操作之前调用。我不了解numpy的内部机制,无法列举要覆盖的所有方法。
我如何实现一个执行此检查的np.ndarray
子类?有没有人能提出更好的方法?
更新: 这个类实现了我大部分想要的功能:
class SafeBufferView(np.ndarray):
def __new__(cls, get_buffer, shape=None, dtype=None):
obj = np.ctypeslib.as_array(get_buffer(), shape).view(cls)
if dtype is not None:
obj.dtype = dtype
obj._get_buffer = get_buffer
return obj
def __array_finalize__(self, obj):
if obj is None: return
self._get_buffer = getattr(obj, "_get_buffer", None)
def __array_prepare__(self, out_arr, context=None):
if not self._get_buffer(): raise Exception("Dangling pointer!")
return out_arr
# this seems very heavy-handed - surely there must be a better way?
def __getattribute__(self, name):
if name not in ["__new__", "__array_finalize__", "__array_prepare__",
"__getattribute__", "_get_buffer"]:
if not self._get_buffer(): raise Exception("Dangling pointer!")
return super(np.ndarray, self).__getattribute__(name)
例如:
wrap = MyWrapper()
sb = SafeBufferView(lambda: wrap._cbuf)
sb[:] = np.arange(10)
print(repr(sb))
# SafeBufferView([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)
print(repr(sb[::2]))
# SafeBufferView([0, 2, 4, 6, 8], dtype=int32)
sbv = sb.view(np.double)
print(repr(sbv))
# SafeBufferView([ 2.12199579e-314, 6.36598737e-314, 1.06099790e-313,
# 1.48539705e-313, 1.90979621e-313])
# we have to call the destructor method of `wrap` explicitly - `del wrap` won't
# do anything because `sb` and `sbv` both hold references to `wrap`
wrap.__del__()
print(sb) # Exception: Dangling pointer!
print(sb + 1) # Exception: Dangling pointer!
print(sbv) # Exception: Dangling pointer!
print(np.sum(sb)) # Exception: Dangling pointer!
print(sb.dot(sb)) # Exception: Dangling pointer!
print(np.dot(sb, sb)) # oops...
# -70104698
print(np.extract(np.ones(10), sb))
# array([251019024, 32522, 498870232, 32522, 4, 5,
# 6, 7, 48, 0], dtype=int32)
# np.copyto(sb, np.ones(10, np.int32)) # don't try this at home, kids!
我相信还有其他边缘情况我可能遗漏了。
更新2:我已经尝试使用
weakref.proxy
,正如@ivan_pozdeev所建议的那样。这是一个好主意,但不幸的是我无法想象它如何与numpy数组一起工作。我可以尝试创建一个对.buffer
返回的numpy数组的弱引用:wrap = MyWrapper()
wr = weakref.proxy(wrap.buffer)
print(wr)
# ReferenceError: weakly-referenced object no longer exists
# <weakproxy at 0x7f6fe715efc8 to NoneType at 0x91a870>
我认为问题在于wrap.buffer
返回的np.ndarray
实例立即超出作用域。一种解决方法是在类初始化时实例化数组,保持对它的强引用,并使.buffer()
getter返回对数组的weakref.proxy
:
class MyWrapper2(object):
def __init__(self, n=10):
# buffer allocated by external library
addr = libc.malloc(C.sizeof(C.c_int) * n)
self._cbuf = (C.c_int * n).from_address(addr)
self._buffer = np.ctypeslib.as_array(self._cbuf)
def __del__(self):
# buffer freed by external library
libc.free(C.addressof(self._cbuf))
self._cbuf = None
self._buffer = None
@property
def buffer(self):
return weakref.proxy(self._buffer)
然而,在缓冲区仍被分配时,如果我创建了第二个对同一数组的视图,则会出现问题:
wrap2 = MyWrapper2()
buf = wrap2.buffer
buf[:] = np.arange(10)
buf2 = buf[:] # create a second view onto the contents of buf
print(repr(buf))
# <weakproxy at 0x7fec3e709b50 to numpy.ndarray at 0x210ac80>
print(repr(buf2))
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int32)
wrap2.__del__()
print(buf2[:]) # this is bad
# [1291716568 32748 1291716568 32748 0 0 0
# 0 48 0]
print(buf[:]) # WTF?!
# [34525664 0 0 0 0 0 0 0
# 0 0]
这个问题很严重——在调用wrap2.__del__()
之后,我不仅可以读写buf2
,它是一个numpy数组视图,对应于wrap2._cbuf
,甚至可以读写buf
,这是不可能的,因为wrap2.__del__()
将wrap2._buffer
设置为None
。
cffi
(您应始终使用而不是ctypes
)具有内置支持gc
方法的删除器),那么您就不必担心无效的弱引用。 - o11c_buffer = None
赋值并不会释放_buffer
,因为其他数组仍然引用它。如果在指针准备好被释放之前手动调用释放指针的函数,那么程序就会出问题。 - user2357112