在C扩展段错误中创建numpy数组 [英] creating numpy array in c extension segfaults

查看:78
本文介绍了在C扩展段错误中创建numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想通过创建一个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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆