Search code examples
pythonccpython

Py_BuildValue segmentation fault


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 ?


Solution

  • 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