简体   繁体   中英

C++ Struct inheritance in Cython

I'm wrapping a C++ library with cython. In the headers file, there are some structs that inherit from other structs, like so:

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

How should this look in my cdef extern... block?

Using C++ in Cython doesn't mention anything special:

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

Wrapper class:

#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

Example:

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

To build it you need to instruct pyximport to use 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM