YLS
YLS

Reputation: 73

Cython: how to pass a c++ class as an argument to a Cython class that wraps the c++ class?

I am fighting with CYTHON, trying to make a copy of a C++ class in a Python class. I the .pxd I have:

cdef extern from "MyCppClass.h":
    cdef cppclass MyCppClass:
        MyCppClass ()
        int        Copy(MyCppClass * Source)


cdef class MyPyClass:
    cdef MyCppClass * thisptr
    cdef copy(self, MyCppClass *s)

and in the .pyx I have

cdef class MyPyClass: 
    def __init__(self): 
        self.thisptr = new MyCppClass ()

    cdef copy(self, MyCppClass * s):    
         self.thisptr.Copy(s)

The compilation is ok.

Then I try to use it in another Cython module:

A=new MyCppClass()
pA=MyPyClass()
… do some stuff on A
p1.copy(A)

And I get the usual “cannot convert to Python object” I have tried a lot of things to copy, like :

 cdef getThisptr(self):
    return self.thisptr

A=new MyCppClass()
pA=MyPyClass()
B=pA.getThisptr()
B.Copy(A)

But nothing works!

It sounds very basic in Cython, but I am still waiting for a solution…

Upvotes: 0

Views: 596

Answers (1)

DavidW
DavidW

Reputation: 30890

You're missing cimport. In order for Cython to know about your cdef defined types and functions you need to add

from module_name cimport MyPyClass

Otherwise it just assumes that Copy is a Python function accepting a Python object.

The relevant bit of documentation

Upvotes: 1

Related Questions