在 Cython 中使用智能指针进行动态分配的数组
Using Smart Pointers in Cython for Dynamically Allocated Arrays
我正在为带有签名
的函数调用编写一个Python包装器
double** foo(double** arrayIn, int dim1, int dim2);
并且需要在我的 Python 包装器中构建 arrayIn
。 here. However, since Cython includes support for smart pointers, I would prefer to implement that solution. One way to do this would be a combination of malloc and a unique_ptr with a custom deleter. Another (simpler) solution would be to use the allocator class from libcpp.
给出了一种可能的解决方案
import numpy as np
cimport numpy as np
from libcpp.memory cimport unique_ptr, allocator
def testArray(int dim1, int dim2):
cdef allocator[double *] ptr_al
cdef unique_ptr[double *] myptr
cdef np.ndarray arr
cdef double[:,:] carr
myptr.reset(ptr_al.allocate(dim1))
arr = np.ndarray((dim1,dim2),dtype=np.float64,order='C')
carr = arr
myptr.get()[0] = &carr[0,0]
myptr.get()[1] = &carr[1,0]
myptr.get()[2] = &carr[2,0]
这段代码可以正确编译和执行(使用 Cython 24.1、Python 3.5、VS2015)。我担心的是是否一切都会被正确释放/垃圾收集。我的理解是Python负责ndarray
,unique_ptr
应该负责allocator
创建的double *[]
。这是正确的,还是代码会造成内存泄漏?有没有一种方法可以验证所有内容都已正确解除分配?
Is this correct, or will the code create a memory leak?
我认为这不应该泄漏。
Is there a way I could verify that everything has been properly deallocated?
您可以循环调用 testArray
并查看进程内存是线性增长还是保持不变。由于您知道 dim1
和 dim2
,如果某些内容未正确释放,您可以估计内存泄漏大小。
在更复杂的情况下,还有其他方法可以测试内存泄漏:C 库的调试版本会告诉您是否已释放所有已分配的内存。此外,还有 valgrind
和 clang
的 leaksanitizer
等工具,但在您的情况下,我会使用循环。
我正在为带有签名
的函数调用编写一个Python包装器double** foo(double** arrayIn, int dim1, int dim2);
并且需要在我的 Python 包装器中构建 arrayIn
。 here. However, since Cython includes support for smart pointers, I would prefer to implement that solution. One way to do this would be a combination of malloc and a unique_ptr with a custom deleter. Another (simpler) solution would be to use the allocator class from libcpp.
import numpy as np
cimport numpy as np
from libcpp.memory cimport unique_ptr, allocator
def testArray(int dim1, int dim2):
cdef allocator[double *] ptr_al
cdef unique_ptr[double *] myptr
cdef np.ndarray arr
cdef double[:,:] carr
myptr.reset(ptr_al.allocate(dim1))
arr = np.ndarray((dim1,dim2),dtype=np.float64,order='C')
carr = arr
myptr.get()[0] = &carr[0,0]
myptr.get()[1] = &carr[1,0]
myptr.get()[2] = &carr[2,0]
这段代码可以正确编译和执行(使用 Cython 24.1、Python 3.5、VS2015)。我担心的是是否一切都会被正确释放/垃圾收集。我的理解是Python负责ndarray
,unique_ptr
应该负责allocator
创建的double *[]
。这是正确的,还是代码会造成内存泄漏?有没有一种方法可以验证所有内容都已正确解除分配?
Is this correct, or will the code create a memory leak?
我认为这不应该泄漏。
Is there a way I could verify that everything has been properly deallocated?
您可以循环调用 testArray
并查看进程内存是线性增长还是保持不变。由于您知道 dim1
和 dim2
,如果某些内容未正确释放,您可以估计内存泄漏大小。
在更复杂的情况下,还有其他方法可以测试内存泄漏:C 库的调试版本会告诉您是否已释放所有已分配的内存。此外,还有 valgrind
和 clang
的 leaksanitizer
等工具,但在您的情况下,我会使用循环。