Home > Blockchain >  Py_BuildValue segmentation fault
Py_BuildValue segmentation fault

Time:01-03

I am trying to run a simple python code from a C program but I get a segmentation fault at the line pArgs = Py_BuildValue("s",(char*)"Greg");

Here is the python code I want to run:

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

Here is my C program:

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

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

I am working on Ubuntu 20.4

The python code launched from Idle works and the files are in the same directory the name of the python file is main.py

Can you tell me what I'm doing wrong ?

CodePudding user response:

pArgs must be a tuple. Add parentheses to the format string:

pArgs = Py_BuildValue("(s)",(char*)"Greg"); 

I didn't get a segmentation fault but a clear error message, so perhaps you have a build issue as well.

TypeError: argument list must be a tuple

CodePudding user response:

As you told me I replaced pArgs = Py_BuildValue("s",(char*)"Greg");

by pArgs = Py_BuildValue("(s)",(char *)"137912500");.

As you told me, I was in the wrong directory so I added PySys_SetPath(L".");.

Here is my corrected 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;
}

Thank you again for your help.

  • Related