2012-03-20 15 views
6

私はcythonでC++ライブラリをラッピングしています。ヘッダファイルには、他の構造体から継承するいくつかの構造体はそうのような、ありますCythonでのC++の構造継承

struct A { 
    int a; 
}; 
struct B : A { 
    int b; 
}; 

どのようにすべきである私のcdef extern...ブロックでこの表情!

答えて

5

Using C++ in Cythonは、特別なことを言及していない:

#file: pya.pyx 
cdef extern from "a.h": 
    cdef cppclass A: 
     int a 
    cdef cppclass B(A): 
     int b 

ラッパークラス:

#file: pya.pyx 
cdef class PyB: 
    cdef B* thisptr 
    def __cinit__(self): 
     self.thisptr = new B(); 
    def __dealloc__(self): 
     del self.thisptr 
    property a: 
     def __get__(self): return self.thisptr.a 
     def __set__(self, int a): self.thisptr.a = a 
    property b: 
     def __get__(self): return self.thisptr.b 
     def __set__(self, int b): self.thisptr.b = b 

例:

import pyximport; pyximport.install(); # pip install cython 

from pya import PyB 

o = PyB() 
assert o.a == 0 and o.b == 0 
o.a = 1; o.b = 2 
assert o.a == 1 and o.b == 2 

もしC++を使用するpyximportを指示する必要があり、それを構築するには:

#file: pya.pyxbld 
import os 
from distutils.extension import Extension 

dirname = os.path.dirname(__file__) 

def make_ext(modname, pyxfilename): 
    return Extension(name=modname, 
        sources=[pyxfilename, "a.cpp"], 
        language="c++", 
        include_dirs=[dirname]) 
+0

structのためにcppclassを使用できますか?もしそうなら、私はクラス継承を行うことができるように見え、それは私の問題を解決するはずです:http://wiki.cython.org/gsoc09/daniloaf/progress#Inheritance – colinmarc

+0

@colinmarc:私はcython 0.15で試してみました。作品;ドキュメントは古いバージョンを記述することがあります。大きな 'struct {..};はC++の' class {public:..}; 'に相当します。 – jfs

+0

あなたの助けてくれてありがとう! – colinmarc