Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Struct inheritance in Cython

Tags:

c++

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?

like image 933
colinmarc Avatar asked Mar 20 '12 04:03

colinmarc


1 Answers

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])
like image 143
jfs Avatar answered Oct 12 '22 13:10

jfs