Code snippets‎ > ‎C++‎ > ‎Boost‎ > ‎

Python

An example creating a python-interface to a C++ program PythonBoost.tgz

#include <boost/python.hpp>
 
#include "hello.h"
 
using namespace boost::python;
 
BOOST_PYTHON_MODULE(hello_python)
{
  def("greet", greet);
 
  class_<Hello_world_class>("Hello_world")
    .def("greet", &Hello_world_class::greet)
    .def("bye", &Hello_world_class::greet2)
    .def("__iter__", iterator< Hello_world_class >())
    .def("numbers", 
         range(&Hello_world_class::begin,
               &Hello_world_class::end))
    ;
}

#include <boost/python.hpp>

#include "hello.h"

using namespace boost::python;

BOOST_PYTHON_MODULE(hello_python)
{
def("greet", greet);

class_<Hello_world_class>("Hello_world")
.def("greet", &Hello_world_class::greet)
.def("bye", &Hello_world_class::greet2)
.def("__iter__", iterator< Hello_world_class >())
.def("numbers",
  range(&Hello_world_class::begin,
        &Hello_world_class::end))
;
}

/// Author: Nico Kruithof
/// Just a standard C++ class with some methods etc.
 
#ifndef HELLO_H
#define HELLO_H
 
#include <list>
 
char const* greet();
 
class Hello_world_class {
public:
  typedef std::list<int>::iterator iterator;
 
  Hello_world_class();
  char const* greet();
  char const* greet2();
 
  iterator begin();
  iterator end();
 
private:
  std::list<int> lst;
};
 
#endif // HELLO_H

/// Author: Nico Kruithof
/// Implementation of the Hello_world_class
 
#include "hello.h"
 
char const* greet()
{
   return "hello, world";
}
 
 
Hello_world_class::Hello_world_class() {
  lst.push_back(1);
  lst.push_back(2);
  lst.push_back(3);
  lst.push_back(4);
}
 
char const* Hello_world_class::greet()
{
   return "Hello_world_class::hello, world";
}
 
char const* Hello_world_class::greet2()
{
   return "bye, world";
}
 
Hello_world_class::iterator 
Hello_world_class::begin() {
  return lst.begin();
}
 
Hello_world_class::iterator 
Hello_world_class::end() {
  return lst.end();
}


OBJ= hello.o hello_interface.o

CXXFLAGS += -I/usr/include/python2.4 -fPIC
LDADD+= -lboost_python

all: hello_python.so

hello_python.so: $(OBJ)
$(CXX) $(CXXFLAGS) -shared -o hello_python.so $(OBJ) $(LDADD)

clean:
rm -f *.so *.o

Other approaches

ċ
pythonboost.tgz
(1k)
Nico Kruithof,
Jul 25, 2011, 1:54 PM
Comments