最近,我一直试图用C++编写一个函数,该函数将双倍向量转换为字符串向量。我想在Python解释器上运行它,所以我使用Pybind11来接口C++和python。这就是我目前所拥有的,
#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) {
//using namespace boost::multiprecision;
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();
}现在,使用命令行中的以下命令,将其编译为共享库:
c++ -O3 -shared -std=gnu++11 -I ../include `python-config --cflags --ldflags --libs` num2StringVectorPyBind.cpp -o num2String.so -fPIC -lquadmath其中./include是pybind11包含的位置。编译后启动python并使用,
import num2String
values = [[10, 20], [30, 40]]
num2String.num2StringVector(values)我得到以下错误,“不兼容函数参数。支持以下参数类型”。在这里,它给出了可能的类型列表,这很奇怪,因为我只是尝试使用一个向量作为函数参数,根据pybind11的文档,这是一个受支持的数据类型:http://pybind11.readthedocs.io/en/latest/basics.html#supported-data-types
是因为我有一个矢量向量( 2d向量)而这是不支持的吗?
发布于 2016-05-11 04:07:33
您只需额外一行代码就可以完成此任务:
#include <pybind11/stl.h>根据文献资料
支持下列基本数据类型:开箱即用(有些可能需要额外的扩展报头)。
在包括pybind11/stl.h之前
>>> import num2String
>>> num2String.num2StringVector([[1, 2], [3, 4, 5]])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Incompatible function arguments. The following argument types are supported:
1. (std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >) -> std::vector<std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::allocator<std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >在包含pybind11/stl.h和重新编译共享库之后:
>>> import num2String
>>> num2String.num2StringVector([[1, 2], [3, 4, 5]])
[['1', '2'], ['3', '4', '5']]https://stackoverflow.com/questions/37146908
复制相似问题