1

I am a newbie to Cython. I am trying to create a Cython wrapper for Python of the following C++ code example. The example below is just a mocked up example which illustrates what I am doing in my project and the issue I am having.

C++ class

A.h

class A {
  public:
    A();
    B * newB(){
      return new B(this, "");
    }
};

B.h

class B {
  public:
    B(A * a, const char * cwd);
};

In Cython:

classes.pxd file:

cdef extern from "A.h":
    cdef cppclass A:
        A() except +
        B * newB()
// Both classes in same .pxd file
cdef extern from "B.h":

classes.pyx file:

cimport classes
from libcpp cimport bool

cdef class PyA:
    cdef classes.A *thisptr
    def __cinit__(self):
        self.thisptr = new classes.A()
    def newB(self):
        cdef PyB val = PyB()
        val.thisxptr = classes.newB()
        return val

cdef class PyB:
     cdef classes.B *thisxptr

     def __cinit__(self):
        self.thisxptr = NULL
     def __dealloc__(self):
        if self.thisxptr != NULL:
           del self.thisxptr

In summary class B should be created via the newB() method in class A, mainly because class A certain key properties and resources which class B will need. But I am getting the following error:

Cannot convert Python object to 'B *'

gansub
  • 1,164
  • 3
  • 20
  • 47
ond1
  • 691
  • 6
  • 10
  • I think this is just a couple of typos. 1) the `if` in your `__dealloc__` is the wrong way round. 2) `val.thisxptr = self.thisptr.newB()` - as you've written in you aren't finding a suitable `A` to call `newB` on – DavidW Apr 18 '19 at 10:18
  • Oh yes the if in dealloc should be a check on not NULL – ond1 Apr 18 '19 at 10:24
  • 2) What I have at the moment is : val.thisxptr = classes.thisptr.newB() But this give the error mentioned in the post. Thanks – ond1 Apr 18 '19 at 10:28
  • 1
    `self` not `classes` (and you need to add `self` as a function argument, like you would in Python). `classes.thisptr` doesn't exist. The error is unhelpful, but it's assuming that it might be able to find a Python function with that name at runtime (which would return a Python object) – DavidW Apr 18 '19 at 10:37
  • Oh yes missed that too. It always difficult to mock up an example from real code without running it – ond1 Apr 18 '19 at 10:39
  • Thanks @DavidW your solution worked. – ond1 Apr 18 '19 at 11:54

0 Answers0