PythonからC++クラスを呼び出す
2007年12月4日21:19
python

SIP を使い C++ クラスを Python から呼び出してみました。
他にも boostSWIG などあるらしいけど、こいつは軽快。良いかも。

たとえばこんな C++ クラス word.h があったとして、

class Word {
private:
    char* _word;
public:
    Word(const char*);
    const char* str() const { return _word; }
    void set(const char*);
    char* reverse() const;
};

sip を使いゴニョゴニョした後、

$ python
>>> from word import Word
>>> w=Word('abc')
>>> w.str()
'abc'
>>> w.reverse()
'cba'
>>> w.set('xyz')
>>> w.str()
'xyz'

こんなふうに Python からクラスとして扱えます。
"operator=" などサポートして無いものもあるらしいけど、スゴイ^^


作るものは C++ のヘッダに似てるけど word.sip

%Module word 0
class Word {
%TypeHeaderCode
#include 
%End
public:
    Word(const char*);
    const char* str() const;
    void set(const char*);
    char* reverse() const;
};
configure.py
import os
import sipconfig

# The name of the SIP build file generated by SIP and used by the build
# system.
build_file = "word.sbf"

# Get the SIP configuration information.
config = sipconfig.Configuration()

# Run SIP to generate the code.
os.system(" ".join([config.sip_bin, "-c", ".", "-b", build_file, "word.sip"]))

# Create the Makefile.
makefile = sipconfig.SIPModuleMakefile(config, build_file)

# Add the library we are wrapping.  The name doesn't include any platform
# specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the
# ".dll" extension on Windows).
makefile.extra_libs = ["word"]

# Generate the Makefile itself.
makefile.generate()

あとはビルドすればできあがり。

$ g++ -fPIC -o word.o -c word.cpp
$ ar cr libword.a word.o
$ sip -c . word.sip
$ python configure.py
$ make

参考サイト


コメントはありません