2
3

More than 5 years have passed since last update.

CythonでC++のstructを読む場合

Last updated at Posted at 2015-08-13

C++のstrcutはclassの特殊な定義なのでcdef structではなく、cdef cppclassを使った方が良い。clangだと継承とか何もしてないstructを読むときにcdef structを使うと動かない(2015年8月現在)。

cythonのドキュメントにどこにも書いてなくて、継承したstructを読み込む場合なんかも分からなくて困る。

参考

cdef structしちゃう場合

hoge.h
typedef struct {
    int moke;
    double fuga;
} HogeStruct;
hoge.pxd
cdef extern from "hoge.h" nogil:
    cdef struct HogeStruct:
        int fuga
        double piyo

hoge.pyx

def foo():
    cdef HogeStruct bar


コレでやると、pyx内のstruct HogeStruct barで、elaborated type refers to a typedefが出てしまう。struct HogeStruct __pyx_v_bar;というのが生成されるのでstructそのものの定義文と衝突する。

cppclassを使う

特に単純にstructじゃなくてcppclassを使えば良い

hoge.h
typedef struct {
    int moke;
    double fuga;
} HogeStruct;
hoge.pxd
cdef extern from "hoge.h" nogil:
    cdef cppclass HogeStruct:
        int fuga
        double piyo

hoge.pyx

def foo():
    cdef HogeStruct bar

それだけ。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3