Skip to content

Instantly share code, notes, and snippets.

Last active July 7, 2019 19:33
What would you like to do?
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

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