[C++-sig] very basic: calling python function from c++

Nicodemus nicodemus at globalite.com.br
Thu Sep 11 00:04:47 CEST 2003

Hi Roel,

Roel Vanhout wrote:

> Hello everybody, I'm only just starting out with boost.python and with 
> python embedding and I have a very basic question. I have found 
> examples of how to get an object into c++ from python and call 
> functions on it, but what I'm trying to do is to get a function 
> pointer to a python function and call that function with two 
> parameters. Basically I have two numbers and users can enter an 
> expression into the gui of the c++ program like this:
> return num1 + num2
> I thought that then in my c++ program, I'd prepend 'function 
> calculate(num1, num2):' to that string, indent the expresson properly 
> and then run the whole thing in python, passing the two numbers that I 
> have in my c++ program to the python function. So I'm looking for a 
> way to get a function pointer that I can pass two numbers and that 
> returns a double. I hope I made myself clear - can anyone help me? 
> Thanks in advance.

If you only want to evaluate a Python expression, use PyRun_String:

PyObject* PyRun_String(char *str, int start, PyObject *globals, PyObject 

    Return value: New reference.
    Execute Python source code from str in the context specified by the
    dictionaries globals and locals. The parameter start specifies the
    start token that should be used to parse the source code.

    Returns the result of executing the code as a Python object, or NULL
    if an exception was raised.

For "start" use Py_eval_input, and wrap the result in a boost::python's 
object. Example (untested):

    boost::python::object pyresult = PyRun_String("(1 + 4) * 3", 
Py_eval_input, NULL, NULL);
    double result = boost::python::extract<double>(pyresult);

If you want to make some variables avaiable for the user ("x", "y", 
etc), create a dict and pass it as the globals parameter of the function.

See the chapter Python/C API of the Python documentation for more info.


More information about the Cplusplus-sig mailing list