python-PyDict_SetItemString segfaults
作者:互联网
我正在尝试为Python3写一个简单的C扩展,当我尝试向字典中添加字符串时它会出现段错误.这是我的代码:
#include <stdio.h>
#include <Python.h>
int main() {
PyObject* dict_p = PyDict_New();
char *val = "idjewijjd";
PyObject* val_p = PyUnicode_FromString(val);
const char *key = "dhsjdshj";
for (int j=0; j<8; j++) {
printf("%d\n", PyUnicode_READ_CHAR(val_p,j));
}
int r = PyDict_SetItemString(dict_p, key, val_p);
return 0;
}
我像这样gcc t.c $(python3-config –includes –libs)编译并运行它.我得到以下输出:
$./a.out
105
100
106
101
119
105
106
106
Segmentation fault (core dumped)
这是gdb回溯:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff78d9b38 in PyUnicode_InternInPlace () from /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0
(gdb) bt
#0 0x00007ffff78d9b38 in PyUnicode_InternInPlace () from /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0
#1 0x00007ffff78b3818 in PyDict_SetItemString () from /usr/lib/x86_64-linux-gnu/libpython3.6m.so.1.0
#2 0x0000555555554d7f in main () at t.c:16
我找不到代码本身的错误.我编译错了吗?
解决方法:
您忘记了初始化解释器:
Py_Initialize();
嵌入Python的程序必须在尝试调用任何Python函数之前初始化解释器.对于由已经初始化的解释器加载的扩展模块,这不是必需的.
标签:c-3,python,python-c-api 来源: https://codeday.me/bug/20191011/1896076.html