Skip to content

Instantly share code, notes, and snippets.

@andreasgrv
Last active Jul 7, 2019
Embed
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{
public:
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;
break;
}
w += token + gap;
}
this -> word = w;
}
py::list drow::get_chars(){
py::list char_vec;
for (auto c : word){
char_vec.append(c);
}
return char_vec;
}
BOOST_PYTHON_MODULE(drow){
py::class_<drow>("drow", py::init<std::string>())
.def(py::init<py::list>())
.def("get_chars", &drow::get_chars)
.def_readwrite("word", &drow::word);
}
drow.so:
g++ -Wall -shared -fPIC -o drow.so 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
@andreasgrv
Copy link
Author

andreasgrv commented Feb 13, 2015

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

In the same folder (where drow.so 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

@jingpengw
Copy link

jingpengw commented Jun 18, 2015

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

@andreasgrv
Copy link
Author

andreasgrv commented Nov 5, 2015

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: http://www.boost.org/doc/libs/1_59_0/libs/python/doc/v2/reference.html

@andreasgrv
Copy link
Author

andreasgrv commented Dec 27, 2015

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)
;

@roggerfq
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