亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕娘9325324 2023-04-18 11:04:06
我想使用py::dict來自 C++ 的 a 。但operator[]似乎沒有定義,我在這里或 pybind11 文檔中找不到有關如何添加鍵/值對或返回鍵值的任何信息?編輯:也許也很重要的一點是我有整數作為鍵。edit2:需要使用py::int_()
查看完整描述

2 回答

?
qq_花開花謝_0

TA貢獻1835條經驗 獲得超7個贊

我看到operator[]定義為py::dict,例如:


m.def("test", [](){

    py::dict d;

    d[py::int_{0}] = "foo";

    return d;

});

>>> example.test()

{10: 'foo'}


查看完整回答
反對 回復 2023-04-18
?
海綿寶寶撒

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


查看完整回答
反對 回復 2023-04-18
  • 2 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號