为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 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 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信