我試圖從C傳遞數組到python並執行簡單的算術運算numpy.prod
,但遇到了分段錯誤。有誰能幫我指出哪裏出了問題?謝謝!Python C API分段錯誤
#include <Python.h>
#include <stdio.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "/share/apps/anaconda2/pkgs/numpy-1.10.4-py27_1/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h"
double Array[4] = {1.0, 2.0, 3.0, 4.0};
double call_func(PyObject *func, double array[]){
PyObject *args;
PyObject *kwargs;
PyObject *result;
npy_intp dims[1] = {4};
double retval;
PyGILState_STATE state = PyGILState_Ensure();
if (!PyCallable_Check(func)){
printf("%s", "Function is not callable!\n");
}
args = PyArray_SimpleNewFromData(1, dims, NPY_FLOAT32, array);
kwargs = NULL;
result = PyObject_Call(func, args, kwargs);
Py_DECREF(args);
Py_XDECREF(kwargs);
if (PyErr_Occurred()){
PyErr_Print();
}
if (!PyFloat_Check(result)){
printf("%s", "Callable did not return a float!");
}
retval = PyFloat_AsDouble(result);
Py_DECREF(result);
PyGILState_Release(state);
return retval;
}
PyObject *import_name(const char *modname, const char *symbol){
PyObject *mymodule = PyImport_ImportModule(modname);
return PyObject_GetAttrString(mymodule, symbol);
}
void main(){
PyObject *myfunc;
double retval;
import_array();
Py_Initialize();
myfunc = import_name("numpy", "prod");
retval = call_func(myfunc, Array);
Py_DECREF(myfunc);
printf("%d\n", retval);
Py_Finalize();
}
(我跟着這個網站http://blog.numerix-dsp.com/2013/08/how-to-pass-c-array-to-python-solution.html?m=1。在程序)
我不明白爲什麼它會導致段錯誤,但是你的'PyArray_SimpleNewFromData()'調用的參數看起來是錯誤的。 'array'是一個'double'數組,但是你使用類型代碼'NPY_FLOAT32'。當然你想'NPY_DOUBLE'或(等同)'NPY_FLOAT64'。 –