How to create a PyObject with a cython class from c/c++?

603 views
Skip to first unread message

Marc-Oliver Gewaltig

unread,
Nov 26, 2012, 4:42:53 AM11/26/12
to cython...@googlegroups.com
Hi,

I am wrapping a large simulator with Cython and at one point in the C++ code I need to create a new Python object that contains
one of the wrapper classes from Cython.

The problem would be solved, if I can define a function, either in C++ or cython which gets a pointer to a cython-wrapped class and returns a python object.

The problem can be illustrated with the Rectangle example from the Cython documentation:


The C++ class Rectangle is wrapped by the Python class PyRectangle.

My Question: How can I write a function (in C/C++ or Cython) 

PyObject *to_PyObject(Rectangle *rect) ?

When I try something like

cdef object to_pyobject(Rectangle *arg):
     return PyRectangle(arg)

or

def to_pyobject(Rectangle *arg):
     return PyRectangle(arg)

Cython complains that it 'rect.pyx:32:27: Cannot convert 'Rectangle *' to Python object'

Any Ideas how to do this?

Thanks

Marc-Oliver

Marc-Oliver Gewaltig

unread,
Nov 26, 2012, 7:56:33 AM11/26/12
to cython...@googlegroups.com



def to_pyobject(Rectangle *arg):
     return PyRectangle(arg)

Cython complains that it 'rect.pyx:32:27: Cannot convert 'Rectangle *' to Python object'

Any Ideas how to do this?


I forgot to add that I changed the definition of class PyRectangle as to accept a pointer to a Rectangle  in its __cinit__ method:

cdef class PyRectangle:
  cdef Rectangle *thisptr
  def __cinit__(self, Rectangle* ptr):
      self.thisptr=ptr

-- mog

Robert Bradshaw

unread,
Nov 26, 2012, 11:50:35 AM11/26/12
to cython...@googlegroups.com
__cinit__ methods can't take non (convertible from) Python types, as
they need to be able to receive their arguments from Python when
constructed from Python. Instead write the less pleasant

cdef to_pyobject(Rectangle *arg):
rect = PyRectangle()
rect.thisptr = arg

(When cdef class methods are supported, this could be done there.)

- Robert

Marc-Oliver Gewaltig

unread,
Nov 28, 2012, 2:34:46 AM11/28/12
to cython...@googlegroups.com

__cinit__ methods can't take non (convertible from) Python types, as
they need to be able to receive their arguments from Python when
constructed from Python. Instead write the less pleasant

cdef to_pyobject(Rectangle *arg):
    rect = PyRectangle()
    rect.thisptr = arg

(When cdef class methods are supported, this could be done there.)


This does the trick. Thanks for the explanation.

Marc-Oliver
 
Reply all
Reply to author
Forward
0 new messages