【问题标题】:return custom struct as python object(which aslo could be none) in pybind11?在pybind11中将自定义结构返回为python对象(也可能没有)?
【发布时间】:2022-01-05 05:25:50
【问题描述】:

我想返回一个自定义结构作为 python 对象,它也可以是无。我尝试了两个 API:

struct Database {
  UserModel *get_user1(const std::string &user_name) const;
  std::optional<UserModel> get_user2(const std::string &user_name) const;
};

但这两个 API 似乎都不起作用。 你能帮帮我吗?

【问题讨论】:

  • 您要返回什么? DataBaseUserModel?
  • @Nimrod,将UserModel作为python对象返回,它可以是pythonNone。 APIget_userDatabase的一个方法,也是一个python对象。

标签: python c++ optional pybind11


【解决方案1】:

原来是我的错。我没有在 mysql C 连接器的结果集中获取正确的数据元素。

当我使用 pybind11 构建的模块时,我的 C++ 编译器/运行时(macOS clang-12)没有抛出任何异常。

最后,在我修复了我的错误后,这两个 API 都可以正常工作:

  • UserModel *get_user1(const std::string &amp;user_name) const(创建新实例并返回pybind11,如果不存在用户则返回nullptr
  • std::optional&lt;UserModel&gt; get_user2(const std::string &amp;user_name) const(将实例副本返回到 pybind11,如果不存在用户,则返回 std::nullopt

就我个人而言,我更喜欢第二个 API,因为它避免了原始指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-04
    • 2018-03-16
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 2021-10-02
    相关资源
    最近更新 更多