[C++-sig] Calling python function from C++

Bjorn Pettersen BPettersen at NAREX.com
Wed Nov 13 05:18:31 CET 2002


> From: David Abrahams [mailto:dave at boost-consulting.com] 
> 
> "Bjorn Pettersen" <BPettersen at NAREX.com> writes:
> 
[snip]
> >
> > My test code is:
> >
> >     PyRun_String(
> >         "def hello(s):              \n"
> >         "    return 'hello ' + s    \n",
> >         Py_file_input, ns, ns);
 
[snip]
 
> Which means you're leaking a reference here.

Thanks (bug in my testapp, my library does the right thing ;-)

> >     PyObject* fn = PyRun_String("hello", Py_eval_input, ns, ns);
[snip]
> >     object hello = object(handle<>(borrowed(fn)));
> 
> Why are you using borrowed()? That causes another reference 
> to be leaked.

It was the only example I could find of converting a PyObject* to an
object ;-) Safe to say I was a little confused by the handle
documentation also...

[snip]

> You want something like:
> 
>   handle<> fn = PyRun_String("hello", Py_eval_input, ns, ns);
>   object hello(fn);
>   std::string cpp_res = extract<std::string>(hello("world"));

Ah.. that actually makes sense now. Thanks a bunch.

-- bjorn

ps: the way Python functions are exposed is extremely cool, especially
for embedded apps!




More information about the Cplusplus-sig mailing list