Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

python - PyDict_SetItemString segfaults

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
", PyUnicode_READ_CHAR(val_p,j));
    }

    int r = PyDict_SetItemString(dict_p, key, val_p);
    return 0;
}

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)

Here is the gdb backtrace:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You forgot to initialize the interpreter:

Py_Initialize();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...