Interfacing C++ and Python: Difference between revisions

From LPTMS Wiki
Jump to navigation Jump to search
(Created page with "== References == * [http://www.boost.org/doc/libs/release/libs/python/doc interfacing C++ and Python] via Boost == Quick start == * command line under linux :> g++ -c test.cp...")
 
No edit summary
Line 6: Line 6:


* command line under linux
* command line under linux
  :> g++ -c test.cpp
  :> g++ -shared myfile.cpp -I/usr/include/python2.6 -lboost_python -o myfile.so -fPIC
 
 
This compiles the basic example below:


<source lang="cpp">
<source lang="cpp">
int main ()
//        myfile.h   
struct World
{
{
  return 0;
  void set(std::string msgin) {this->msg=msgin ;}
  std::string greet() {return msg ;}
  std::string msg;
} ;
</source>
 
<source lang="cpp">
//        myfile.cpp  #include <boost/python.hpp>
 
#include "myfile.h"
 
using namespace boost::python;
 
BOOST_PYTHON_MODULE(hello)
{
  def("greet", greet, "return one of three parts of a greeting");
  class_<World>("World")
    .def("greet",&World::greet)
    .def("set",&World::set)
    ;  
}
}
</source>
which runs as
<source lang="py">
In [1]: import hello
In [2]: planet = hello.World()
In [3]: planet.set('howdy')
In [4]: planet.greet()
Out[4]: 'howdy'
</source>
</source>

Revision as of 10:36, 14 October 2011

References

Quick start

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


This compiles the basic example below:

<source lang="cpp"> // myfile.h struct World {

 void set(std::string msgin) {this->msg=msgin ;}
 std::string greet() {return msg ;}
 std::string msg;

} ; </source>

<source lang="cpp"> // myfile.cpp #include <boost/python.hpp>

  1. include "myfile.h"

using namespace boost::python;

BOOST_PYTHON_MODULE(hello) {

 def("greet", greet, "return one of three parts of a greeting");
 class_<World>("World")
   .def("greet",&World::greet)
   .def("set",&World::set)
   ; 

} </source>

which runs as <source lang="py"> In [1]: import hello In [2]: planet = hello.World() In [3]: planet.set('howdy') In [4]: planet.greet() Out[4]: 'howdy' </source>