creating numpy array in c extension segfaults

梦想的初衷 提交于 2020-03-22 03:50:37

问题


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;
}

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?


回答1:


Typical usage of PyArray_SimpleNew is for example

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[].

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)


来源:https://stackoverflow.com/questions/25494858/creating-numpy-array-in-c-extension-segfaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!