2 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
我看到operator[]定義為py::dict,例如:
m.def("test", [](){
py::dict d;
d[py::int_{0}] = "foo";
return d;
});
>>> example.test()
{10: 'foo'}

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以看到 operator[] 有兩個(gè)重載采用 a py::handleor string literal, sod["xxx"]或d[py::int_{0}]work 而不是 d[0] (在編譯時(shí)會(huì)被錯(cuò)誤地解析為無(wú)效的字符串文字,并會(huì)導(dǎo)致運(yùn)行時(shí)段錯(cuò)誤)
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)]
為了使事情更簡(jiǎn)單,使用 pybind11::cast() 將任何支持的 C++ 類型顯式轉(zhuǎn)換為相應(yīng)的 python 類型,如下所示:
std::string key="xxx";
d[pybind11::cast(1)] = 2
d[pybind11::cast(key)] = 3
添加回答
舉報(bào)