I recently tried to write a function in C ++ that converts a double vector to a string vector. I want to run this from a python interpreter, so I use Pybind11 for the C ++ and Python interface. This is what I still have
#include <pybind11/pybind11.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
std::string castToString(double v) {
std::string str = boost::lexical_cast<std::string>(v);
return str;
}
std::vector<std::vector<std::string> > num2StringVector(std::vector<std::vector<double> >& inputVector) {
std::vector<std::vector<std::string> > outputVector;
std::transform(inputVector.begin(), inputVector.end(), std::back_inserter(outputVector), [](const std::vector<double> &iv) {
std::vector<std::string> dv;
std::transform(iv.begin(), iv.end(), std::back_inserter(dv), &castToString);
return dv;
});
return outputVector;
}
namespace py = pybind11;
PYBIND11_PLUGIN(num2String) {
py::module m("num2String", "pybind11 example plugin");
m.def("num2StringVector", &num2StringVector, "this converts a vector of doubles to a vector of strings.");
m.def("castToString", &castToString, "This function casts a double to a string using Boost.");
return m.ptr();
}
Now it compiles to the shared library using the following command from the command line:
c++ -O3 -shared -std=gnu++11 -I ../include `python-config --cflags --ldflags --libs` num2StringVectorPyBind.cpp -o num2String.so -fPIC -lquadmath
where is included .. / include, where is pybind11. After compiling, run python and use
import num2String
values = [[10, 20], [30, 40]]
num2String.num2StringVector(values)
: " " ". , , , , pybind11, :
http://pybind11.readthedocs.io/en/latest/basics.html#supported-data-types
, ( 2d), ?