Skip to content

Instantly share code, notes, and snippets.

@avli
Created July 3, 2014 07:45
Show Gist options
  • Save avli/b0bf77449b090b768663 to your computer and use it in GitHub Desktop.
Save avli/b0bf77449b090b768663 to your computer and use it in GitHub Desktop.
test of boost::python vector to python lits conversion
#include <boost/python.hpp>
#include <vector>
#include <string>
char const* yay()
{
return "Yay!";
}
std::vector<int> myrange(int N) {
std::vector<int> vi;
for (int i = 0; i < N; i++) {
vi.push_back(i);
}
return vi;
}
struct World
{
void set(std::string msg) { this-> msg = msg; }
std::string greet() { return msg; }
std::string msg;
std::vector<int> digits();
};
std::vector<int> World::digits() {
std::vector<int> vi;
for (int i = 0; i <= 9; i++) {
vi.push_back(i);
}
return vi;
}
template<class T>
struct vector_to_python
{
static PyObject* convert(const std::vector<T>& vec)
{
boost::python::list* l = new boost::python::list();
for(std::size_t i = 0; i < vec.size(); i++)
(*l).append(vec[i]);
return l->ptr();
}
};
BOOST_PYTHON_MODULE(libyay)
{
using namespace boost::python;
def("yay", yay);
def("myrange", myrange);
class_<World>("World")
.def("greet", &World::greet)
.def("set", &World::set)
.def("digits", &World::digits)
;
to_python_converter<std::vector<int, std::allocator<int> >, vector_to_python<int> >();
}
@avli
Copy link
Author

avli commented Jul 3, 2014

Code examples taken from here and here.

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