在C语言中创建numpy数组

s3fp2yjn  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(70)

我只是想在开始写扩展之前先创建一个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调用上出现了segfaults,我不明白为什么。我试图遵循前面的一些问题(例如numpy array C apiC array to PyArray)。我做错了什么?

c9x0cxw0

c9x0cxw01#

例如,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)

相关问题