问题描述
我只是想通过创建一个numpy数组开始,甚至还没有开始编写扩展名.这是一个超级简单的程序:
I'm just trying to start off by creating a numpy array before I even start to write my extension. Here is a super simple program:
#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 array C api 和).我在做什么错了?
This program segfaults on the PyArray_SimpleNew
call and I don't understand why. I'm trying to follow some previous questions (e.g. numpy array C api and C array to PyArray). What am I doing wrong?
推荐答案
例如,PyArray_SimpleNew
的典型用法
int nd = 2;
npy_intp dims[] = {3,2};
PyObject *alpha = PyArray_SimpleNew(nd, dims, NPY_DOUBLE);
请注意,nd
的值不得超过数组dims[]
的元素数.
Note that the value of nd
must not exceed the number of elements of array dims[]
.
ALSO::扩展名 必须调用 import_array()
来设置C API的功能指针表.例如.在Cython中:
ALSO: The extension must call import_array()
to set up the C API's function-pointer table. E.g. in 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)
这篇关于在C扩展段错误中创建numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!