Hello World / plɹoM ollǝH

Programmers Live in Vain

boost::pythonでC++のコードをpythonから呼んでみる

まずは単純な関数やクラスを自作してpythonから読んでみます。

C++

いつものようにdllプロジェクトを作成してboostとpythonのlibをリンクします。

出力されるファイルの拡張子をdllからpydに変更しておきます。

#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>

class Vector3
{
public:
    float x, y, z;

    Vector3 Add(const Vector3& rhs)
    {
        Vector3 ret;
        ret.x = this->x + rhs.x;
        ret.y = this->y + rhs.y;
        ret.z = this->z + rhs.z;
        return ret;
    }
};

Vector3 Cross(const Vector3& lhs, const Vector3& rhs)
{
    Vector3 ret;
    ret.x = lhs.y * rhs.z - lhs.z * rhs.y;
    ret.y = lhs.z * rhs.x - lhs.x * rhs.z;
    ret.z = lhs.x * rhs.y - lhs.y * rhs.x;
    return ret;
}

BOOST_PYTHON_MODULE(hoge)
{
    boost::python::class_<Vector3>("Vector3")
        .def_readwrite("x", &Vector3::x)
        .def_readwrite("y", &Vector3::y)
        .def_readwrite("z", &Vector3::z)
        .def("Add", &Vector3::Add);

    boost::python::def("Cross", Cross);
}

Python

C++プロジェクトをビルドしてできあがったpydをpythonでimportします。

モジュールの属性リストを表示する
# conding: utf-8
import hoge
print(dir(hoge))

boost::pythonで定義したクラスと関数がpythonにも公開されています。

['Cross', 'Vector3', '__doc__', '__file__', '__loader__', '__name__', '__package__']
実際に使ってみる
# conding: utf-8
import hoge

a = hoge.Vector3()
b = hoge.Vector3()

a.x = 1.0
a.y = 0.0
a.z = 0.0

b.x = 0.0
b.y = 1.0
b.z = 0.0

c = a.Add(b)
print(c.x, c.y, c.z)

c = hoge.Cross(a, b)
print(c.x, c.y, c.z)

pythonからVector3クラスの演算を実行することに成功しました。

1.0 1.0 0.0
0.0 0.0 1.0

boost::python便利です。詳しくは公式ドキュメントを読んでください。

Boost.Python - 1.58.0