Skip to content

Boost:Python

파이썬과 c++ 의 연동을 지원하는 프레임워크. 빠르고 균일하게 c++ 클래스의 함수나 객체들을 파이썬에서 사용할 수 있게 만들어 주며 다른 특별한 도구를 추가로 실행할 필요가 없다. (c++ 컴파일러만 있으면 된다.)

Simple example

// greet.cpp
#include <stdexcept>

char const* greet(unsigned x)
{
  static char const* const msgs[] = { "hello", "Boost.Python", "world!" };
  if (x > 2) 
    throw std::range_error("greet: index out of range");
  return msgs[x];
}

#include <boost python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(hello)
{
  def("greet", greet, "return one of 3 parts of a greeting");
}

Class example

#include <boost/python.hpp>

#include <string>

class HelloWorld
{
public:
    HelloWorld() : m_Msg("World") {}
    HelloWorld(std::string msg) : m_Msg(msg) {}
    ~HelloWorld() {}

    void sayHello(void) { std::cout << "Hello " << m_Msg << std::endl; }
    void setMsg(std::string msg) { m_Msg = msg; }
    std::string getMsg(void) { return m_Msg; }

private:
    std::string m_Msg;
};

using namespace boost::python;

BOOST_PYTHON_MODULE(PythonModuleTest)
{
    class_<HelloWorld>("HelloWorld")
        .def(init<std::string>())
        .def("sayHello", &HelloWorld::sayHello)
        .def("setMsg", &HelloWorld::setMsg)
        .def("getMsg", &HelloWorld::getMsg);
}

See also

Favorite site