[C++-sig] Re: C++ Python Scope Problems
David Abrahams
dave at boost-consulting.com
Thu Nov 25 01:26:26 CET 2004
"Ralf W. Grosse-Kunstleve" <rwgk at yahoo.com> writes:
> --- Chris Targett <xin at xlevus.net> wrote:
>
>> I see. But if i do:
>>
>> import libHg # name of C++ library
>> foo = libHg.Test()
>> print id(foo.var1), foo.var1
>> foo.var1 += 1
>> print id(foo.var1), foo.var1
>>
>> I get
>> 135523772 0
>> 135523760 1
>>
>> Which clearley shows the varible is 'rebound'
>
> I got me worried..., but what you show above works correctly as one would
> expect. However, it has not much to do with your original problem. When you
> don't get the expected result you are doing something far more complex:
>
> PyObject *pFunc = getPyFunc("testScript","testFunction");
> call<void>(pFunc, this);
>
> David, please correct me if I am wrong: I think the call<>() must create a
> temporary Python object with a copy of "this". The temporary disappears at the
> end of the function call.
Correct.
> David, is there a way to create a temporary with a pointer to "this", e.g.
> call<void>(pFunc, *this);
> ?
Of course:
call<void>(pFunc, boost::python::ptr(this));
> To the OP: as in real life, there are good and bad neighborhoods. In
> my judgement you are in a bad neighborhood. If you call Python from
> C++ I am wondering why you are in C++ in the first place. There will
> not be much of a speed gain compared to a pure Python solution.
Not everybody does this for speed, though.
> Here is a simple rule that works very well for me:
>
> Never call Python from C++.
It doesn't work for anyone who has a C++ library with virtual
functions that they want to override from Python. It is often
acceptable to have your Python subclasses of some base be slow, since
your C++ derived classes will be fast. If speed matters you can start
moving those subclasses into C++.
Even if you're not writing subclasses, similar arguments apply to any
scenario where you call Python from C++ (there's an isomorphism in
there ;->).
> This side-steps a lot of potential surprises like your original
> problem. In addition, I'd bet your code will be better organized.
It probably does help to keep things organized, and it's a good idea
when applicable, especially if performance is very important to you.
But it doesn't apply to every valid use case.
--
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com
More information about the Cplusplus-sig
mailing list