Wrap the C ++
code in cython
so that it can be called from python
,
I wrote various things like that,
This time, I will explain a little about how to write shared_ptr
in cython
.
I have a little habit, but once I get used to it, it's okay.
As usual,
--Classes written in C ++
--Functions written in C ++
By wrapping with cython
, it will be configured so that it can be called from python
.
Here, as an example
--C ++ has a class called Test_CPP. `` --
C ++ Test_CPP has a method called test_function`
I will say.
It's probably easier to understand by looking at the code than it is explained.
Py_Test_CPP
is the class that wraps Test_CPP
.
test.pyx
from cython.operator cimport dereference as deref
from libcpp.memory cimport shared_ptr, make_shared
cdef class Py_Test_CPP:
cdef shared_ptr[Test_CPP] ptr
def __cinit__(self, int arg1):
self.ptr = make_shared[Test_CPP](arg1)
def test_function(self):
return deref(self.ptr).test_function()
First,
I'm importing because I use dereference
, shared_ptr, make_shared
.
At this time, it was necessary to hold the pointer of the class object on the C ++
side as a property,
This time I write it as cdef shared_ptr [Test_CPP] ptr
and keep it as shared_ptr
.
In __cinit __
which is the constructoron the
cython side,
make_shared
toself.ptr = make_shared [Test_CPP](arg1)
By using like, self.ptr on the cython side is made a shared pointer
.
At def test_function (self)
, I wrap the function test_functionon the
C ++ side,
In that case, access the entity as deref (self.ptr)
and call the function on the C ++ side from there
, and it will work.
I summarized the writing method when using shared_ptr
with cython
as a memorandum.
This time around here.
end.
Recommended Posts