Skip to content

Instantly share code, notes, and snippets.

Last active July 7, 2019 19:33
Show Gist options
  • Save andreasgrv/1d4f9320552ce9bb6dba to your computer and use it in GitHub Desktop.
Save andreasgrv/1d4f9320552ce9bb6dba to your computer and use it in GitHub Desktop.
An example of python boost use for a python - C++ interface utilizing python lists as arguments
#include <boost/python.hpp>
#include <string>
namespace py = boost::python;
class drow{
std::string word;
drow(std::string word): word(word){};
drow(py::list ch);
py::list get_chars();
drow::drow(py::list l){
std::string w {""};
std::string gap {" "};
std::string token;
for (int i = 0; i < len(l) ; i++){
token = py::extract<std::string>(l[i]);
if (i == len(l) -1){
w += token;
w += token + gap;
this -> word = w;
py::list drow::get_chars(){
py::list char_vec;
for (auto c : word){
return char_vec;
py::class_<drow>("drow", py::init<std::string>())
.def("get_chars", &drow::get_chars)
.def_readwrite("word", &drow::word);
g++ -Wall -shared -fPIC -o drow.cpp -std=c++0x -lboost_python -I/usr/include/python2.7
from drow import drow
# create drow instance
d = drow('dog')
# access the word and print it
print d.word
# print the chars
for char in d.get_chars():
print char
# check out if it works for a list
# it will join the words and save them in word variable
d = drow(['cat', 'dog', 'canary'])
# print me joined
print d.word
Copy link

On Debian Wheezy an example of building would be :
g++ -Wall -shared -fPIC -o drow.cpp -std=c++0x -lboost_python -I/usr/include/python2.7

In the same folder (where is) open the python interpreter and:
import drow

known dependencies for Wheezy again (apt-gets):
g++ python-dev libboost-python

Note that the c++0x standard is used

Copy link

this is the best example I have found!
Could you show some data conversion, such as std::size_t.

Copy link

Sorry, only just came across this comment by chance. It's been a long time since I looked into this, maybe you could find something here:

Copy link

I actually worked on a similar bit of code today - example with size_t :

class text {
    size_t length();

class_<text>("Text", init<std::string>())
    .def("__len__", &text::length)

Copy link

roggerfq commented Jul 7, 2019

It is a nice tutorial, excellent to beginning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment