2 回答

TA贡献1835条经验 获得超7个赞
我看到operator[]定义为py::dict,例如:
m.def("test", [](){
py::dict d;
d[py::int_{0}] = "foo";
return d;
});
>>> example.test()
{10: 'foo'}

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