如何在 Pybind11 中将 Python 字典转换为 C++ 对应部分?

Rik*_*ika 6 c++ pybind11

目前我正在尝试将 a 转换py::dict为其对应的C++s std::map。尝试像这样使用自动转换失败:

#include <pybind11/stl.h>
namespace py = pybind11;
using namespace py::literals;
...
py::dict py_kwargs = py::dict("number1"_a = 5, "number2"_a = 42);
auto cpp_kwargs = py_kwargs.cast<std::map<int, int>>();

Run Code Online (Sandbox Code Playgroud)

但有一个例外:

Unable to cast Python instance of type <class 'dict'> to C++ type 'std::map<int,int,std::less<int>,std::allocator<std::pair<int const ,int> > >'
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

另外,我应该如何处理 python 字典具有不同键类型的情况,例如:

Unable to cast Python instance of type <class 'dict'> to C++ type 'std::map<int,int,std::less<int>,std::allocator<std::pair<int const ,int> > >'
Run Code Online (Sandbox Code Playgroud)

在这种情况下我应该如何进行转换?

Rik*_*ika 5

好的,我发现了问题,在此之前我最终进行了如下转换:

map<std::string, int> convert_dict_to_map(py::dict dictionary)
{
    map<std::string, int> result;
    for (std::pair<py::handle, py::handle> item : dictionary)
    {
        auto key = item.first.cast<std::string>();
        auto value = item.second.cast<int>();
        //cout << key << " : " << value;
        result[key] = value;
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

然后,仔细查看:

auto cppmap = kwargs.cast<map<int, int>>();
Run Code Online (Sandbox Code Playgroud)

终于注意到我的问题了。它应该是:

auto cppmap = kwargs.cast<map<std::string, int>>();
Run Code Online (Sandbox Code Playgroud)

当我更改示例字典并稍后恢复更改但忘记更改签名时,我犯了一个错误!

不管怎样,第一个解决方案似乎是更好的选择,因为它允许开发人员Python更好地处理 的动态特性。
也就是说,Python字典很可能包含不同的对(例如string:stringstring:intint:float, 等都在同一字典对象中)。因此,使用第一种粗略方法可以更好地确保在 C++ 中有效地重建项目!