Skip to content

Instantly share code, notes, and snippets.

@andreasgrv
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{
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

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