简体   繁体   English

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

[英]creating numpy array in c extension segfaults

I'm just trying to start off by creating a numpy array before I even start to write my extension. 我只是想通过创建一个numpy数组开始,甚至还没有开始编写扩展名。 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;
}

This program segfaults on the PyArray_SimpleNew call and I don't understand why. 该程序在PyArray_SimpleNew调用上出现段PyArray_SimpleNew ,我不明白为什么。 I'm trying to follow some previous questions (eg numpy array C api and C array to PyArray ). 我正在尝试遵循以前的一些问题(例如numpy数组C apiC数组到PyArray )。 What am I doing wrong? 我究竟做错了什么?

Typical usage of PyArray_SimpleNew is for example 例如, PyArray_SimpleNew典型用法

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

Note that the value of nd must not exceed the number of elements of array dims[] . 请注意, nd的值不得超过dims[]数组的元素数。

ALSO: The extension must call import_array() to set up the C API's function-pointer table. 还:扩展必须调用 import_array()来设置C API的功能指针表。 Eg in Cython: 例如在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM