首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >正确使用PyArray_SimpleNewFromData?

正确使用PyArray_SimpleNewFromData?
EN

Stack Overflow用户
提问于 2020-06-13 19:27:50
回答 1查看 330关注 0票数 0

我正在尝试在python扩展中创建一个numpy数组。PyArray_SimpleNewFromData的调用给了我一个段错误。我试着修复它几个小时,现在我不知道它是如何发生的。下面是一个重现它的自包含示例:

$ cat test.c

代码语言:javascript
运行
复制
#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 3-config --includes) -g -o测试test.c $(python3 3-config --libs)

$ echo "run;bt“| gdb测试

代码语言:javascript
运行
复制
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);
EN

回答 1

Stack Overflow用户

发布于 2020-06-13 20:09:01

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

代码语言:javascript
运行
复制
 Py_Initialize();
 import_array();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62359077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档