Interfacing C++ and Python

From LPTMS Wiki
Revision as of 10:36, 14 October 2011 by Ullmo (talk | contribs)

Jump to: navigation, search


Quick start

  • command line under linux
:> g++ -shared myfile.cpp -I/usr/include/python2.6 -lboost_python -o -fPIC

This compiles the basic example below:

//         myfile.h    
struct World
  void set(std::string msgin) {this->msg=msgin ;}
  std::string greet() {return msg ;}
  std::string msg;
} ;

//         myfile.cpp   #include <boost/python.hpp>

#include "myfile.h"

using namespace boost::python;

  def("greet", greet, "return one of three parts of a greeting");

which runs as

In [1]: import hello
In [2]: planet = hello.World()
In [3]: planet.set('howdy')
In [4]: planet.greet()
Out[4]: 'howdy'