Support for cdef of C++ object references #1695

Open
ferdonline opened this Issue May 3, 2017 · 5 comments

Comments

Projects
None yet
3 participants

When a C++ function returns a reference we are forced to workaround: typically make the call inside a function accepting references

It would be desirable to support
cdef Foo & obj = func_bar()

Cython apparently declares the reference and assigns to it in different steps, which obviously doesn't compile.

Why not just take the address and reference the return value as a pointer?

Contributor

robertwb commented May 21, 2017

References are just pointers that must be assigned at declaration time, which ties in strongly to C++'s scoping (which is at odds with Python/Cython's scoping) which means supporting this would be non-trivial (as well as require other changes, e.g. allowing a cdef definition to occur anywhere). In particular, legal constructions like

if Cond:
    x = ...
common code
if Cond:
    foo(x)

simply wouldn't work (or require interesting gymnastics).

Instead, write cdef Foo* obj = &func_bar() which is just as powerful.

@robertwb robertwb added a commit that referenced this issue May 21, 2017

@robertwb robertwb Explicit error on declaring a reference type.
This is better than generating invalid code; see #1695.
bfd1aa7

ferdonline commented Jul 3, 2017 edited

Another side effect is that
cdef ObjT x = somefunc_returning_a_ObjT()

will invoke the copy assignment operator... without warnings. With arrays the problem goes from performance penalty to compile errors (like when using boost::multi_array)

Instead, write cdef Foo* obj = &func_bar() which is just as powerful.

I was wondering if cython was specially handling that case, but no, it doesn't work.
...xxx:165:34: Taking address of non-lvalue (type Positions)

Contributor

robertwb commented Jul 3, 2017

The cdef Foo* obj = &func_bar() trick only works when func_bar returns a reference. It is correct that an assignment invokes the assignment operator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment