PyDict_SetItemString segfaults [英] PyDict_SetItemString segfaults

查看:172
本文介绍了PyDict_SetItemString segfaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Python3写一个简单的C扩展,当我尝试向字典中添加字符串时,它会出现段错误.这是我的代码:

I am trying to write a simple C extension for Python3, and it segfaults when I try to add a string to a dictionary. Here is my code:

#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)并运行它.我得到以下输出:

I compile it like this gcc t.c $(python3-config --includes --libs) and run it. I get the following output:

$ ./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

我找不到代码本身的错误.我编译错了吗?

I cannot find an error n the code itself. Do I compile it wrong?

推荐答案

您忘了初始化解释器:

Py_Initialize();

嵌入Python的程序必须在尝试调用任何Python函数之前初始化解释器.对于由已初始化的解释器加载的扩展模块,这不是必需的.

A program that embeds Python must initialize the interpreter before attempting to call any Python functions. This is not necessary for extension modules, which are loaded by an already-initialized interpreter.

这篇关于PyDict_SetItemString segfaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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