![]() |
Exposing Classes |
![]() |
![]() |
![]() |
C++ クラスを Python に開扉しよう。
Python に公開したい C++ クラスまたは構造体を考えてみよう。
struct World
{
void set(std::string msg) { this->msg = msg; }
std::string greet() { return msg; }
std::string msg;
};
これを、Boost.Python ラッパ書式に合わせることで、 Python に開示可能である。
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
;
}
これは、開示したいメンバ関数 greet と set のラッパの記述である。 このあと共有ライブラリをビルドすれば、Worldクラスを Python で使えるようになる。 下記は Python セッションの例である。
>>> import hello
>>> planet = hello.World()
>>> planet.set('howdy')
>>> planet.greet()
'howdy'
![]() |
![]() |
![]() |
Copyright © 2002 David Abrahams
Copyright © 2002 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document
is granted provided this copyright notice appears in all copies. This document
is provided "as is" without express or implied warranty, and with
no claim as to its suitability for any purpose.