Hi All,
I was recently introduced to Cython by a coworker. I'm still getting my head wrapped around it and have been playing around with it a bit to understand if it would be a good candidate to wrap a large C++ class library we have. I like the shared_ptr approach highlighted
here.
One difference though is that in my library I have C++ accessor methods that will return a shared_ptr to an object. I'm wondering what is the best way to wrap these efficiently. Here is an example of what I'm trying to do:
from libcpp.memory cimport shared_ptr
from libcpp.string cimport string
from cython.operator cimport dereference as deref
cdef extern from "CBar.hpp":
cdef cppclass CBar:
CBar()
string getName() except *
cdef extern from "CFoo.hpp":
cdef cppclass CFoo:
CFoo()
void setBar(shared_ptr[CBar]) except *
shared_ptr[CBar] getBar() except *
cdef class Bar(object):
cdef shared_ptr[CBar] _thisptr
def __init__(self):
pass
def __cinit__(self):
print "bar.cinit clled"
self._thisptr.reset(new CBar())
@staticmethod
cdef create(shared_ptr[CBar] ptr):
cdef Bar py_obj = Bar()
py_obj._thisptr = ptr
return py_obj
property name:
def __get__(self):
return deref(self._thisptr).getName()
cdef class Foo(object):
cdef shared_ptr[CFoo] _thisptr
def __cinit__(self):
self._thisptr.reset(new CFoo())
property bar:
def __get__(self):
return Bar.create(deref(self._thisptr).getBar())
The issue I have with it, is that if I call the Foo's getBar method from python, a new "CBar" object gets created in the cinit function, which is then immediately replaced by the create function. I'm wonder what is the best way to avoid it. How have other people handle this? Am I going down the wrong rabbit hole in my approach?
Thanks and a appreciate the feedback,
Bryan