Wan*_*ong 5 python numpy python-2.7
我正在尝试为numpy编写一个C扩展来对大数组进行一些计算,但是当我使用"PyArray_SimpleNew"或"PyArray_FromDims"来获取PyArrayObject时,我遇到了一个大问题.这是我的代码:
#include<stdio.h>
#include "Python.h"
#include"arrayobject.h"
static PyObject *MyExtGFV(PyObject *self, PyObject *args)
{
npy_intp dims = 1;
PyArray_SimpleNew(1, &dims, PyArray_FLOAT32);
retuurn Py_BuildValue("i", 1);
}
static PyMethodDef my_ext_methods[] =
{
{"GFV", MyExtGFV, METH_VARARGS, "used to generate feature vectors"},
{NULL, NULL}
}
PyMODINIT_FUNC initMyExt(void)
{
Py_InitModule("MyExt", my_ext_methods);
}
Run Code Online (Sandbox Code Playgroud)
为了调试它,我删除了函数MyExtGFV()中的大部分代码,只留下
PyArray_SimpleNew(1, &dims, PyArray_FLOAT32);
Run Code Online (Sandbox Code Playgroud)
在它,但当我导入它并在我的python代码中使用它时,它说"python已经停止工作".我已经搜索了这个问题很长一段时间,但似乎没有其他人有同样的问题,它几乎让我感到烦恼,任何帮助将不胜感激!
好的,最后我明白了,init函数应该这样写:
PyMODINIT_FUNC initMyExt(void)
{
Py_InitModule("MyExt", my_ext_methods);
import_array();
}
Run Code Online (Sandbox Code Playgroud)
"import_array();" numpy是必要的,谢天谢地~~