问题描述
我在python中有以下kwargs:
interface_dict = {'type':['linear'],'scope':['ascendant'],height:[-0.4272,0.4272],length:[27.19],'flag':[True]}
interface.py_interface(**interface_dict)
我在C ++中使用pybind11访问这些python值。我正在尝试将这些值存储在这样的变体多图中:
void py_interface(py::kwargs kwarg){
std::multimap<std::string,std::variant<float,bool,int,std::string>> kwargs = {
{"type",(*(kwarg["type"]).begin()).cast<std::string>()},{"scope",(*(kwarg["scope"]).begin()).cast<std::string>()},{"height",(*(kwarg["height"]).begin()).cast<float>()},{"length",(*(kwarg["length"]).begin()).cast<float>()},{"flag",(*(kwarg["flag"]).begin()).cast<bool>()}
};
kwargs.insert(std::pair<std::string,std::string>>("height",/* question how do I access the second value of height to store it here */));
我的问题是如何获取高度的第二个值(0.4272)。我尝试使用.end(),但出现错误:
kwargs.insert(std::pair<std::string,(*(kwarg["height"]).end()).cast<float>())); //error unable to cast Python instance to C++ type
有人可以帮我吗?
解决方法
您可以使用py::sequence
来按索引访问项目。只要确保元素存在于给定的索引下即可:
std::multimap<std::string,std::variant<float,bool,int,std::string>> kwargs = {
{"type",(*(kwarg["type"]).begin()).cast<std::string>()},{"scope",(*(kwarg["scope"]).begin()).cast<std::string>()},{"height",py::sequence(kwarg["height"])[1].cast<float>()},{"length",(*(kwarg["length"]).begin()).cast<float>()},{"flag",(*(kwarg["flag"]).begin()).cast<bool>()}
};
另一种选择是增加通过begin()
调用创建的迭代器:
std::multimap<std::string,(*(kwarg["height"].begin()++)).cast<float>()},(*(kwarg["flag"]).begin()).cast<bool>()}
};