在C扩展中创建numpy数组导致段错误

6 投票
1 回答
3064 浏览
提问于 2025-04-18 18:30

我现在想先创建一个numpy数组,然后再开始写我的扩展程序。这里有一个非常简单的程序:

#include <stdio.h>
#include <iostream>
#include "Python.h"
#include "numpy/npy_common.h"
#include "numpy/ndarrayobject.h"
#include "numpy/arrayobject.h"

int main(int argc, char * argv[])
{
    int n = 2;
    int nd = 1;
    npy_intp size = {1};
    PyObject* alpha = PyArray_SimpleNew(nd, &size, NPY_DOUBLE);
    return 0;
}

这个程序在调用 PyArray_SimpleNew 的时候出现了段错误,我不明白为什么。我试着参考了一些之前的问题(比如 numpy数组的C接口C数组转PyArray)。我哪里做错了呢?

1 个回答

6

使用 PyArray_SimpleNew 的典型方式,比如说:

int nd = 2;
npy_intp dims[] = {3,2};
PyObject *alpha = PyArray_SimpleNew(nd, dims, NPY_DOUBLE);

需要注意的是,nd 的值不能超过数组 dims[] 中元素的数量。

另外:这个扩展必须调用 import_array() 来设置 C API 的函数指针表:

这个函数必须在一个模块的初始化部分被调用,该模块会使用 C-API。它会导入存储函数指针表的模块,并将正确的变量指向它。

例如,在 Cython 中:

import numpy as np
cimport numpy as np

np.import_array()  # so numpy's C API won't segfault

cdef make_array():
  cdef np.npy_intp element_count = 100
  return np.PyArray_SimpleNew(1, &element_count, np.NPY_DOUBLE)

撰写回答