2012-03-20 35 views
6

Tôi đang gói thư viện C++ với cython. Trong tập tin tiêu đề, có một số cấu trúc mà kế thừa từ cấu trúc khác, như vậy:C++ Cấu trúc kế thừa trong Cython

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

Làm thế nào nên nhìn này trong cdef extern... khối của tôi?

Trả lời

5

Using C++ in Cython không đề cập đến bất cứ điều gì đặc biệt:

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

Wrapper lớp:

#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 

Ví dụ:

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 

Để xây dựng nó, bạn cần phải hướng dẫn pyximport sử dụng C++:

#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

Tôi chỉ có thể sử dụng cppclass cho struct? Nếu vậy, có vẻ như tôi có thể làm kế thừa lớp, và điều đó sẽ giải quyết vấn đề của tôi: http://wiki.cython.org/gsoc09/daniloaf/progress#Inheritance – colinmarc

+0

@colinmarc: Tôi đã thử nó trên cython 0,15 và nó công trinh; tài liệu có thể mô tả phiên bản cũ hơn. Với 'struct {..};' tương đương với 'class {public: ..};' trong C++. – jfs

+0

cảm ơn sự giúp đỡ của bạn! – colinmarc