[SciPy-user] Weave - accessing object data members?
eric jones
eric at enthought.com
Mon May 26 16:06:33 EDT 2003
Hey Fernando,
> Hi all,
>
> I suppose that expecting weave.inline to magically make the following
> work:
>
> ###############
> from weave import inline
> class bunch: pass
>
> def oaccess():
> x=bunch()
>
> x.a = 1
>
> code = """ // BROKEN!
> // Try to emulate Python's: print 'x.a',x.a
> std::cout << "x.a " << x.a << std::endl;
> """
> inline(code,['x'])
>
> oaccess()
> ###############
>
>
> is probably a bit too much, right :) ? It would have to extract all
the
> members of 'x', and make all the right type work in C++. This sounds
> pretty much near impossible.
Yep.
> Things like these are what makes you really
> love the convenience of Python vs C/C++ :)
>
> But I wonder what the best way to access object members from within
the C
> code is. So far my typical approach is just to make undotted copies
of
> everything I'll need once inside C/C++:
>
> a = x.a
> b = x.b
>
> inline("do_stuff_with(a,b);", ['a','b'])
>
> But there may be a better way to do it that I've missed. I pored over
the
> weave tutorial and the auto-generated C++ code, but I couldn't really
find
> any ideas for a better solution.
The attr method will work:
###################################
from weave import inline
class bunch: pass
def oaccess():
x=bunch()
x.a = 1
code = """
// Try to emulate Python's: print 'x.a',x.a
std::cout << (int)x.attr("a") << (int)x.attr("a") <<
std::endl;
"""
inline(code,['x'])
oaccess()
The attr method returns a py::object. Notice you have to cast this
value to an integer before writing it out. I pretty sure this could
actually be fixed by overloading the << operator for py::object --
please do if you feel comfortable trying it.
eric
More information about the SciPy-User
mailing list