Home > Net >  Python C API segmentation fault when importing library in py file
Python C API segmentation fault when importing library in py file

Time:01-05

I am trying to run a python program from a C program.

However when I add the line import signal in my .py file I get a segmentation fault.

Using GDB I saw that the line pModule = PyImport_Import(pName); returns a NULL value.

(gdb) print pModule
$1 = (PyObject *) 0x0

When I remove the line import signal in python the module loads correctly. Do you know how to fix this ?

Here is my python code:

import signal

def main(person):
    print("DANS PYTHON")
    return "What's up "   person;

And here is my C code:

#include <stdio.h>
#include <Python.h>

void main(void) {
    Py_Initialize();
    PyObject *pName,*pName2, *pModule, *pFunc, *pArgs, *pValue;
    PySys_SetPath(L".");    
    pName = PyUnicode_FromString((char*)"main");                 
    pModule = PyImport_Import(pName);   
    pFunc = PyObject_GetAttrString(pModule, (char*)"main");      
    pArgs = Py_BuildValue("(s)",(char *)"137912500"); 
    pValue = PyObject_CallObject(pFunc, pArgs);                  
    Py_Finalize();                                               
    return;
}

I am working with Ubuntu 20.04

Thanks in advance for your help

CodePudding user response:

I'm on Ubuntu 20.04 also and I have the same problem.

I found that the sys.path is ['.'] when run from a C program. So it search only in the current directory.

I was able to run your script by adding these 2 lines before import signal

import sys
sys.path.append("/usr/lib/python3.8")

import signal

def main(person):
    print("DANS PYTHON")
    return "What's up "   person

To get the folder of the signal module I run :

$ python3
Python 3.8.10 (default, Nov 26 2021, 20:14:08) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import signal
>>> signal.__file__
'/usr/lib/python3.8/signal.py'
>>> 

I think that a configuration is missing somewhere but I have no clue about that.

Edit : you can also simply add the path in your C program:

PySys_SetPath(L".:/usr/lib/python3.8");
  •  Tags:  
  • Related