我正在编写一个简单的c代码,它将向python返回一个双数组。我成功地编译了代码,没有出错,并且可以生成.so
文件以在python中导入。然而,当我从Python环境调用包装的C函数时,我得到core dump
。我附上下面的c代码,这样错误就可以重现了。如果有人指点我,让我明白我错在哪里,导致core dump
错误,我将不胜感激?在调试时,我发现错误源在
pyArr = (PyArrayObject*) PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, ptr);
但我无法解决这个问题。我也尝试过在line 6
中使用static double array
,但得到了相同的core dump
问题。感谢您的帮助。你知道吗
#include <Python.h>
#include <numpy/arrayobject.h>
#include <numpy/ndarrayobject.h>
extern "C" {
static PyObject* func_wrap(PyObject* , PyObject* args)
{
double* ptr;
ptr = (double *) malloc(4 * sizeof(double));
*ptr = 1.0; *(ptr+1) = 2.0; *(ptr+2) = 3.0; *(ptr+3) = 4.0;
PyArrayObject* pyArr;
npy_intp dims[1];
dims[0] = 4;
pyArr = (PyArrayObject*)PyArray_SimpleNewFromData(1, dims, NPY_BYTE, ptr);
PyArray_ENABLEFLAGS(pyArr, NPY_ARRAY_OWNDATA); /* numpy array takes the ownership afterwards */
return Py_BuildValue("O", pyArr);
}
static PyMethodDef CppMethods[] = {
{"func", func_wrap, METH_VARARGS, "returns numpy 1d array"},
{NULL, NULL, 0, NULL}
};
// Define module information
static struct PyModuleDef mydemo = {
PyModuleDef_HEAD_INIT,
"mydemo",
"mydemo Module",
-1,
CppMethods
};
// Init function for module
PyMODINIT_FUNC PyInit_mydemo(void) {
import_array();
return PyModule_Create(&mydemo);
}
}
目前没有回答
相关问题 更多 >
编程相关推荐