I tried to learn how to use the new C++ wrapping functionality in cython:
http://github.com/certik/cpp_test
I have the following C++ classes (taken from cython tests, only added
a subclass):
http://github.com/certik/cpp_test/blob/master/cppwrap_lib.h
and here is the wrapper:
http://github.com/certik/cpp_test/blob/master/cppwrap.pyx
and a test:
http://github.com/certik/cpp_test/blob/master/test.py
import cppwrap
a = cppwrap.DoubleKeeper(5)
print a.transmogrify(6)
b = cppwrap.DoubleKeeper2(5)
print b.transmogrify(6)
print cppwrap.transmogrify_from_cpp(a, 6)
print cppwrap.transmogrify_from_cpp(b, 6)
if you run it, it will print:
$ ./test.py
Initializing DoubleKeeper
30.0
Initializing DoubleKeeper
Initializing DoubleKeeper2
11.0
30.0
11.0
So correct methods are being called in the function:
def transmogrify_from_cpp(DoubleKeeper obj not None, double value):
"""
>>> d = DoubleKeeper(2.0)
>>> d.transmogrify(3.0) == 6.0
True
"""
return cppwrap_lib.transmogrify_from_cpp(obj.keeper, value)
except that the subclass DoubleKeeper2 is being initialized twice ---
once with DoubleKeeper, second time with DoubleKeeper2.
Is there some way to fix this?
Thanks for any tips,
Ondrej
This fixes it:
--- a/cppwrap.pyx
+++ b/cppwrap.pyx
@@ -16,7 +16,7 @@ cdef class DoubleKeeper:
"""
cdef cppwrap_lib.DoubleKeeper* keeper
- def __cinit__(self, double number):
+ def __init__(self, double number):
print "Initializing DoubleKeeper"
self.keeper = new cppwrap_lib.DoubleKeeper(number)
@@ -34,7 +34,7 @@ cdef class DoubleKeeper:
cdef class DoubleKeeper2(DoubleKeeper):
- def __cinit__(self, double number):
+ def __init__(self, double number):
print "Initializing DoubleKeeper2"
self.keeper = new cppwrap_lib.DoubleKeeper2(number)
It greatly helps for me to formulate my question in the email. Thanks
for listening. :)
Ondrej
Perhaps you write a helper cdef Keeper* _create_keeper() in both
classes (calling new on the appropriate classes), and then call it in
the base class...
--
Lisandro Dalcin
---------------
CIMEC (INTEC/CONICET-UNL)
Predio CONICET-Santa Fe
Colectora RN 168 Km 472, Paraje El Pozo
Tel: +54-342-4511594 (ext 1011)
Tel/Fax: +54-342-4511169