[C++-sig] pyCXX example of a callback

Stefan Seefeld seefeld at sympatico.ca
Wed Nov 15 20:54:19 CET 2006


apocalypznow wrote:
> Hi,
> 
> Can anyone post a simple pyCXX example of a callback into python?  My 

I don't know what 'pyCXX' is, so let's assume you mean boost.python.

> python function should allow a string passed as a parameter, and returns 
> a string, ie:
> 
> def somepythonCB(s_in):
>      s_out = dosomethingtoinputstringandreturnoutputstring(s_in)
>      return s_out

The answer is very similar to one I gave in a previous question:

namespace bpl = boost::python;
bpl::dict global;
bpl::exec_file("your_file.py", global, global);      // load the definition
bpl::object func = global["somepythonCP"];           // extract python function
bpl::object retn = func(input);                      // call it with input string
std::string value = bpl::extract<std::string>(retn); // extract return value

The magic here is that boost.python already has builtin support for
conversion between std::string and python's str.
Please note that the 'exec_file' function is only in CVS, not in the last
official release. See my previous posts for more on that.

HTH,
		Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list