在C语言中创建numpy数组

s3fp2yjn  于 2024-01-06  发布在  其他
关注(0)|答案(1)|浏览(287)

我只是想在开始写扩展之前先创建一个numpy数组。下面是一个超级简单的程序:

  1. #include <stdio.h>
  2. #include <iostream>
  3. #include "Python.h"
  4. #include "numpy/npy_common.h"
  5. #include "numpy/ndarrayobject.h"
  6. #include "numpy/arrayobject.h"
  7. int main(int argc, char * argv[])
  8. {
  9. int n = 2;
  10. int nd = 1;
  11. npy_intp size = {1};
  12. PyObject* alpha = PyArray_SimpleNew(nd, &size, NPY_DOUBLE);
  13. return 0;
  14. }

字符串
这个程序在PyArray_SimpleNew调用上出现了segfaults,我不明白为什么。我试图遵循前面的一些问题(例如numpy array C apiC array to PyArray)。我做错了什么?

c9x0cxw0

c9x0cxw01#

例如,PyArray_SimpleNew的典型用法是

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

字符串
注意nd的值不能超过数组dims[]的元素数。

另外:扩展必须调用import_array()来设置C API的函数指针表:

这个函数必须在使用C-API的模块的初始化部分调用。它导入存储函数指针表的模块并将正确的变量指向它。
例如,在Cython中:

  1. import numpy as np
  2. cimport numpy as np
  3. np.import_array() # so numpy's C API won't segfault
  4. cdef make_array():
  5. cdef np.npy_intp element_count = 100
  6. return np.PyArray_SimpleNew(1, &element_count, np.NPY_DOUBLE)

展开查看全部

相关问题