使用PyArray_SimpleNewFromData的正确方法?

问题描述 投票:0回答:1

我正在尝试在python扩展名中创建一个numpy数组。PyArray_SimpleNewFromData的调用给了我一个段错误。我试图将其修复几个小时,现在我不知道该如何发生了。这是一个自我复制的示例:

$ cat test.c

#define PY_SSIZE_T_CLEAN
#include <Python.h>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include "numpy/arrayobject.h"

 void main(int argc, char ** argv) {
    char* data;
    npy_intp dims[2];
    data = malloc(20);
    if(NULL == data)
        exit(-1);
    strncpy(data,"helloworld",10);
    dims[0] = 5;
    dims[1] = 2;
    PyObject* result = PyArray_SimpleNewFromData(2, dims, NPY_BYTE, data);
}

$ gcc $(python3-config --includes)-g -o test test.c $(python3-config --libs)

$ echo“ run; bt” | gdb测试

GNU gdb (Ubuntu 8.1-0ubuntu3.2) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...done.
(gdb) Starting program: /home/mag/project/mouse/test ;bt
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x0000555555554dc6 in main (argc=1, argv=0x7fffffffddc8) at test.c:16
16      PyObject* result = PyArray_SimpleNewFromData(2, dims, NPY_BYTE, data);
python-3.x numpy-ndarray python-extensions
1个回答
0
投票

可能未初始化numpy。将以下行添加到main()的开头有帮助:

 Py_Initialize();
 import_array();
© www.soinside.com 2019 - 2024. All rights reserved.