kshitijsoni1
kshitijsoni1

Reputation: 43

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);
}

Upvotes: 4

Views: 3614

Answers (2)

tynn
tynn

Reputation: 39873

You can use the explicit constructors for integers PyInt_FromLong or PyLong_FromLong instead.

You can find functions like this for any type you can create with Py_BuildValue and get a little type safety on top.

Upvotes: 2

falsetru
falsetru

Reputation: 369444

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).

Upvotes: 6

Related Questions