Pybind11类型E

2024-09-30 06:32:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近一直试图在C++中编写一个函数,把一个双倍向量转换成字符串向量。我想从Python解释器中运行这个,所以我使用pybDun11来连接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();
}

现在,使用命令行中的以下命令将其编译到共享库中:

^{pr2}$

其中../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向量)而这是不支持的?在


Tags: stringreturninclude向量pybind11stddoublevector
1条回答
网友
1楼 · 发布于 2024-09-30 06:32:17

您只需额外添加一行代码即可实现此功能:

#include <pybind11/stl.h>

根据the documentation

The following basic data types are supported out of the box (some may require an additional extension header to be included).

在包含pybind11/stl.h之前:

^{pr2}$

在包含pybind11/stl.h并重新编译共享库之后:

>>> import num2String
>>> num2String.num2StringVector([[1, 2], [3, 4, 5]])
[['1', '2'], ['3', '4', '5']]

相关问题 更多 >

    热门问题