【发布时间】:2016-08-17 03:07:32
【问题描述】:
我正在将我的代码从使用 ctypes 接口的 Python/C 传输到使用 Cython 接口的 Python/C++。新接口将使我更易于维护代码,因为我可以利用所有 C++ 功能并且只需要相对较少的接口代码行。
接口代码与小型数组完美配合。但是,在使用大型数组时会遇到分段错误。我一直在解决这个问题,但还没有接近解决方案。我已经包含了一个发生分段错误的最小示例。请注意,它始终出现在 Linux 和 Mac 上,而且 valgrind 也没有给出见解。另请注意,在纯 C++ 中完全相同的示例确实可以正常工作。
该示例包含(部分)C++ 中的稀疏矩阵类。在 Cython 中创建了一个接口。因此,该类可以从 Python 中使用。
C++ 端
sparse.h
#ifndef SPARSE_H
#define SPARSE_H
#include <iostream>
#include <cstdio>
using namespace std;
class Sparse {
public:
int* data;
int nnz;
Sparse();
~Sparse();
Sparse(int* data, int nnz);
void view(void);
};
#endif
sparse.cpp
#include "sparse.h"
Sparse::Sparse()
{
data = NULL;
nnz = 0 ;
}
Sparse::~Sparse() {}
Sparse::Sparse(int* Data, int NNZ)
{
nnz = NNZ ;
data = Data;
}
void Sparse::view(void)
{
int i;
for ( i=0 ; i<nnz ; i++ )
printf("(%3d) %d\n",i,data[i]);
}
Cython 界面
csparse.pyx
import numpy as np
cimport numpy as np
# UNCOMMENT TO FIX
#from cpython cimport Py_INCREF
cdef extern from "sparse.h":
cdef cppclass Sparse:
Sparse(int*, int) except +
int* data
int nnz
void view()
cdef class PySparse:
cdef Sparse *ptr
def __cinit__(self,**kwargs):
cdef np.ndarray[np.int32_t, ndim=1, mode="c"] data
data = kwargs['data'].astype(np.int32)
# UNCOMMENT TO FIX
#Py_INCREF(data)
self.ptr = new Sparse(
<int*> data.data if data is not None else NULL,
data.shape[0],
)
def __dealloc__(self):
del self.ptr
def view(self):
self.ptr.view()
setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize(Extension(
"csparse",
sources=["csparse.pyx", "sparse.cpp"],
language="c++",
)))
Python 端
import numpy as np
import csparse
data = np.arange(100000,dtype='int32')
matrix = csparse.PySparse(
data = data
)
matrix.view() # --> segmentation fault
运行:
$ python setup.py build_ext --inplace
$ python example.py
请注意,data = np.arange(100,dtype='int32') 确实有效。
【问题讨论】:
-
代码太多了。你的minimal reproducible example呢?
-
OK“轨道上的轻量化竞赛”,你说得对!我已经剥离了所有不必要的东西
-
一种解决方案似乎是增加对数组的引用数量(在
csparse.pyx中添加为cmets)。但是,我认为我已经有效地破坏了 Python 的部分功能...... -
也许可以,但您必须记住,您的 Python 只是一个基本用 C++ 编写的程序的接口。
标签: python c++ arrays numpy cython