Last active
July 7, 2019 19:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
drow.so: | |
g++ -Wall -shared -fPIC -o drow.so drow.cpp -std=c++0x -lboost_python -I/usr/include/python2.7 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is a nice tutorial, excellent to beginning.