Cython中的C++结构继承 [英] C++ Struct inheritance in Cython

查看:36
本文介绍了Cython中的C++结构继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用cython包装一个C++库。在头文件中,有一些继承自其他结构的结构,如下所示:

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

这在我的cdef extern...块中应该是什么样子?

推荐答案

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

要构建它,您需要指示PXIMPORT使用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])

这篇关于Cython中的C++结构继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆