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
添加回答
舉報