[C++-sig] Re: pyste: current cvs/1_30_00 difference in treatment of overloaded members

David Abrahams dave at boost-consulting.com
Sun May 18 01:33:49 CEST 2003


Nicodemus <nicodemus at globalite.com.br> writes:

> Thanks for the replies so far David, your help is very appreciated!
>
> David Abrahams wrote:
>
>>Oh, sorry.  You can of course stick a function in A_Wrapper which gets
>>you &A::name:
>>
>>        static char const* (A::*a_name())() { return &A::name; }
>>
>
> Hmm... I did that, and added this line to the wrapper:
>
>     .def("name", A_Wrapper::a_name(), &A_Wrapper::default_name)
>
> And in Python:
>
>  >>> from test import *
>  >>> A()
> <test.A object at 0x008B8560>
>  >>> a = A()
>  >>> a.name()
> 'foo'
>  >>> a.get_name()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ReferenceError: Attempt to return dangling pointer to object of type: char
>  >>>
>
> Perhaps am I doing something wrong?

Yes, but it's a separate problem.  See
http://www.boost.org/libs/python/doc/v2/faq.html#dangling

There's often no safe way to wrap virtual functions which return char
const*.  If you think about what has to happen in the dispatching
function you'll see why.

>>>>I think trying to get Python A instances not to have a name method is
>>>>sort of unpythonic, but be that as it may...
>>>> To get overridability, you need to implement A_Wrapper::name() so
>>>>that
>>>>it dispatches into Python.  If you don't want to expose a "name"
>>>>attribute, you'd better implement A_Wrapper::name() something like
>>>>this:
>>>>
>>>>       char const* name()
>>>>       {
>>>>           if (PyObject_HasAttrString(this->self, "name"))
>>>>               return boost::python::call_method<char const*>(self, "name");
>>>>           else
>>>>               return A::name();
>>>>       }
>>>> 
>>>That's what I thought...
>>>
>>
>>But it seems like that's not the solution you're looking for.
>>Unfortunately Python doesn't let you say "who's asking?" before giving
>>out an attribute value, so you can't hide A.name from everything
>>that's not a derived class of A.
>>
>
> This solution would be perfect, except that the Python class can't
> access the default implementation of the method, which is a quite
> common need. 8/

Too bad, I guess.  There's no way to have only partial access in
Python.  Either it's accessible to everyone or to no one.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list