Search code examples
pythoncpython-c-apipython-c-extensionpython-extensions

How to return a value from C to python from C's PyObject type of functions?


I was trying to pass a value by calling C file from python and then return that value from C to python again.

My question is how to do this? Can it possible to use return Py_BuildValue(a+b) kind of thing?

#include <Python.h>

static PyObject *
hello_world(PyObject *self, PyObject *noargs)
{
   int a=5,b=10;

   return Py_BuildValue(a+b); //This is Errorus.
}


static PyMethodDef
module_functions[] = {
    { "hello_world", hello_world, METH_NOARGS, "hello world method" },
    { NULL }
};



PyMODINIT_FUNC
inittesty2(void)
{
    Py_InitModule("testy2", module_functions);
}

Solution

  • Specify the format of the value:

    return Py_BuildValue("i", a+b); // "i" for int
    

    You can find more format unit here (Py_BuildValue documentation).