Created
April 23, 2019 14:29
-
-
Save fernandoc1/1f9d00dd7f0b9ac22ab4745d5fd48f40 to your computer and use it in GitHub Desktop.
Access std::vector in boost::python
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 <iostream> | |
#include <vector> | |
#include <memory> | |
#include <boost/shared_ptr.hpp> | |
#include <boost/python.hpp> | |
#include <boost/python/stl_iterator.hpp> | |
#include <Python.h> | |
template<typename T> inline std::vector<T> pyListToStdVector(const boost::python::object& iterable) | |
{ | |
return std::vector<T>(boost::python::stl_input_iterator<T>(iterable), boost::python::stl_input_iterator<T>()); | |
} | |
template <class T> inline boost::python::list stdVectorToPyList(std::vector<T> vector) | |
{ | |
typename std::vector<T>::iterator iter; | |
boost::python::list list; | |
for(iter = vector.begin(); iter != vector.end(); ++iter) | |
{ | |
list.append(*iter); | |
} | |
return list; | |
} | |
int main() | |
{ | |
Py_Initialize(); | |
boost::python::object mainModule = boost::python::import("__main__"); | |
boost::python::object mainNamespace = mainModule.attr("__dict__"); | |
std::vector<float> valVec; | |
valVec.push_back(1); | |
valVec.push_back(2); | |
valVec.push_back(3); | |
boost::python::list valList = Utils::stdVectorToPyList(valVec); | |
mainModule.attr("valList") = valList; | |
std::string codeStr = | |
"print valList \n"; | |
boost::python::exec(codeStr.c_str(), mainNamespace); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are some useful links:
https://gist.github.com/marcinwol/b8df949bf8009cf856a3
https://github.com/josephturnerjr/boost-python-tutorial/blob/master/part1/hello_world.cpp