[Cython] Class methods returning C++ class references are not dealt with correctly?

Sturla Molden sturla at molden.no
Thu Feb 28 15:34:31 CET 2013


On 28.02.2013 13:58, Yury V. Zaytsev wrote:
> Hi,
>
> I'm sorry if my question would appear to be trivial, but what am I
> supposed to do, if I want to wrap class methods, that return a reference
> to another class?
>
>  From reading the list, I've gathered that apparently the best strategy
> of dealing with references is just to not to use them (convert to
> pointers immediately), because of some scoping rules issues.
>
> It works for me for a simple case of POD types, like
>
>      cdef extern from "test.h":
>          int& foo()
>
>      cdef int* x = &foo()
>
> but in a more complex case, Cython generates incorrect C++ code (first
> it declares a reference, then assigns to it, which, of course, doesn't
> even compile):
>
>      cdef extern from "token.h":
>          cppclass Token:
>              Token(const Datum&) except +
>
>      cdef extern from "tokenstack.h":
>          cppclass TokenStack:
>              Token& top() except +
>
>      cdef Token* tok = &self.pEngine.OStack.top()
>
> <->
>
>      Token *__pyx_v_tok;
>      Token &__pyx_t_5;
>      __pyx_t_5 = __pyx_v_self->pEngine->OStack.top();
>      __pyx_v_tok = (&__pyx_t_5);


This is clearly a bug in Cython. The generated code should be:

       Token *__pyx_v_tok;
       Token &__pyx_t_5 = __pyx_v_self->pEngine->OStack.top();
       __pyx_v_tok = (&__pyx_t_5);


One cannot let a C++ reference dangle:

       Token &__pyx_t_5;  // illegal C++



Sturla















More information about the cython-devel mailing list