【问题标题】:error occurs when I write my own C extension for numpy当我为 numpy 编写自己的 C 扩展时发生错误
【发布时间】:2012-10-14 04:11:03
【问题描述】:

我正在尝试为 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);
}

为了调试它,我删除了MyExtGFV()函数中的大部分代码,只留下了

PyArray_SimpleNew(1, &dims, PyArray_FLOAT32);   

在其中,但是当我将它导入并在我的 python 代码中使用它时,它说“python 已停止工作”。这个问题我google了很久,好像没有人有同样的问题,快把我逼疯了,任何帮助将不胜感激!!!

【问题讨论】:

  • Cython 使编写使用 numpy 的 Python 的 C 扩展变得简单。 example

标签: python numpy python-2.7


【解决方案1】:

好的,终于明白了,init函数应该是这样写的:

PyMODINIT_FUNC initMyExt(void)
{
    Py_InitModule("MyExt", my_ext_methods);
    import_array();
}

"import_array();"对numpy来说是必需的,谢天谢地~~

【讨论】:

  • 你帮了我很多!
  • 再走一步,如果您有多个文件,您可能还需要按照import the api 部分中列出的说明进行操作。 This question 有更多信息
猜你喜欢
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多