猿问

如何在 C++ 中设置 py::dict 的值?

我想使用py::dict来自 C++ 的 a 。但operator[]似乎没有定义,我在这里或 pybind11 文档中找不到有关如何添加键/值对或返回键值的任何信息?

编辑:也许也很重要的一点是我有整数作为键。

edit2:需要使用py::int_()


慕娘9325324
浏览 123回答 2
2回答

qq_花开花谢_0

我看到operator[]定义为py::dict,例如:m.def("test", [](){    py::dict d;    d[py::int_{0}] = "foo";    return d;});>>> example.test(){10: 'foo'}

海绵宝宝撒

您可以看到 operator[] 有两个重载采用 a py::handleor string literal, sod["xxx"]或d[py::int_{0}]work 而不是 d[0] (在编译时会被错误地解析为无效的字符串文字,并会导致运行时段错误)template <typename Derived>class object_api : public pyobject_tag {...&nbsp; &nbsp; /** \rst&nbsp; &nbsp; &nbsp; &nbsp; Return an internal functor to invoke the object's sequence protocol. Casting&nbsp; &nbsp; &nbsp; &nbsp; the returned ``detail::item_accessor`` instance to a `handle` or `object`&nbsp; &nbsp; &nbsp; &nbsp; subclass causes a corresponding call to ``__getitem__``. Assigning a `handle`&nbsp; &nbsp; &nbsp; &nbsp; or `object` subclass causes a call to ``__setitem__``.&nbsp; &nbsp; \endrst */&nbsp; &nbsp; item_accessor operator[](handle key) const;&nbsp; &nbsp; /// See above (the only difference is that they key is provided as a string literal)&nbsp; &nbsp; item_accessor operator[](const char *key) const;你也不能使用 std::string 作为键:std::string key="xxx";d[key] = 1;&nbsp; // failed to compile, must change to d[pybind11::str(key)]为了使事情更简单,使用 pybind11::cast() 将任何支持的 C++ 类型显式转换为相应的 python 类型,如下所示:std::string key="xxx";d[pybind11::cast(1)] = 2d[pybind11::cast(key)] = 3
随时随地看视频慕课网APP

相关分类

Python
我要回答