我试图为python写一个c扩展,以加快我在项目中进行的一些数字计算,而不必将整个项目移植到c语言中去。下面是一个最小的例子。
#include "Python.h"
#include "numpy/arrayobject.h"
#include <math.h>
static PyObject *myFunc(PyObject *self, PyObject *args)
{
PyArrayObject *out_array;
int dims[1];
dims[0] = 2;
out_array = (PyArrayObject *) PyArray_FromDims(1,dims,NPY_DOUBLE);
// return Py_BuildValue("i", 1); // if I swap this return value it works
return PyArray_Return(out_array);
}
static PyMethodDef minExMethiods[] = {
{"myFunc", myFunc, METH_VARARGS},
{NULL, NULL} /* Sentinel - marks the end of this structure */
};
static struct PyModuleDef minExModule = {
PyModuleDef_HEAD_INIT,
"minEx", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
minExMethiods
};
PyMODINIT_FUNC PyInit_minEx(void)
{
return PyModule_Create(&minExModule);
}
谁能建议我可能做错了什么?我在 OS X 10.13.6 上使用 Conda 和 python 3.6 环境。
谢谢
我需要在模块初始化函数中调用import_array()来正确使用numpy的c帮助函数。然后我还得到了PyArray_FromDims被贬值的错误.修复后的代码bellow.
#include "Python.h"
#include "numpy/arrayobject.h"
#include <math.h>
static PyObject *myFunc(PyObject *self, PyObject *args)
{
PyArrayObject *out_array;
npy_intp dims[1];
dims[0] = 2;
out_array = (PyArrayObject *) PyArray_SimpleNew(1,dims,PyArray_DOUBLE);
return PyArray_Return(out_array);
}
static PyMethodDef minExMethiods[] = {
{"myFunc", myFunc, METH_VARARGS},
{NULL, NULL} /* Sentinel - marks the end of this structure */
};
static struct PyModuleDef minExModule = {
PyModuleDef_HEAD_INIT,
"minEx", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
minExMethiods
};
PyMODINIT_FUNC PyInit_minEx(void)
{
PyObject *module = PyModule_Create(&minExModule);
import_array();
return module;
}