如何将 Python dict 转换为 Pybind11 中的 C++ 计数器部分?
How to convert Python dict to the C++ counter part in Pybind11?
目前我正在尝试将 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>>();
有一个例外说明:
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> > >'
我在这里错过了什么?
另外,在旁注中,我应该如何处理 python 字典具有不同键类型的情况,例如:
py::dict py_kwargs = py::dict("name"_a = "World", "number"_a = 42);
在这种情况下我应该如何进行转换?
好的,我发现了问题,在此之前我最终是这样进行转换的:
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;
}
然后,仔细看了下:
auto cppmap = kwargs.cast<map<int, int>>();
终于注意到了我的问题。
应该是:
auto cppmap = kwargs.cast<map<std::string, int>>();
我犯了一个错误,当时我更改了我的示例字典,后来恢复了更改但忘记更改签名!
无论如何,第一个解决方案似乎是更好的选择,因为它允许开发人员更好地利用 Python
的动态特性。
也就是说,Python
字典很可能包含不同的对(例如 string:string
、string:int
、int:float
等都在同一个字典对象中)。因此,使用第一种粗略方法可以更好地确保项目在 C++ 中有效重构!
目前我正在尝试将 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>>();
有一个例外说明:
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> > >'
我在这里错过了什么?
另外,在旁注中,我应该如何处理 python 字典具有不同键类型的情况,例如:
py::dict py_kwargs = py::dict("name"_a = "World", "number"_a = 42);
在这种情况下我应该如何进行转换?
好的,我发现了问题,在此之前我最终是这样进行转换的:
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;
}
然后,仔细看了下:
auto cppmap = kwargs.cast<map<int, int>>();
终于注意到了我的问题。 应该是:
auto cppmap = kwargs.cast<map<std::string, int>>();
我犯了一个错误,当时我更改了我的示例字典,后来恢复了更改但忘记更改签名!
无论如何,第一个解决方案似乎是更好的选择,因为它允许开发人员更好地利用 Python
的动态特性。
也就是说,Python
字典很可能包含不同的对(例如 string:string
、string:int
、int:float
等都在同一个字典对象中)。因此,使用第一种粗略方法可以更好地确保项目在 C++ 中有效重构!