【问题标题】:Function with dynamic return type in pybind11pybind11 中具有动态返回类型的函数
【发布时间】:2023-02-13 04:14:04
【问题描述】:

在 python 中,您可以定义动态返回不同类型的函数:

def func(b):
   if b:
      return 42
   else:
      return "hello"

我如何在 C++ 中实现这样的函数并使用 pybind11 导出它?

理想情况下它会是这样的:

m.def("func", [](bool b) -> py::object {
   if(b)
      return /* something */(42);
   else
      return /* something */("hello");
});

但是,我没有找到如何使用已注册 C++ 类型的对象构造 py::object

这可能吗?

【问题讨论】:

  • 使用std::variant
  • 啊,当然!没想到!谢谢!
  • 你可以,但你应该吗?
  • 这似乎是不明智的事情,但结合新的结构模式匹配,它很有意义。
  • 您能否演示一下 std::variant 的解决方案是什么样子的?

标签: python c++ pybind11


【解决方案1】:

由于@Osyotr 的评论,解决方案非常简单:

#include <variant>
#include <string>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

...

m.def("func", [](bool b) -> std::variant<int, std::string> {
   if(b)
      return {42};
   else
      return {"hello"};
});

PyBind11 自动负责向 Python 端提供 variant 的正确组件。

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2018-03-03
    相关资源
    最近更新 更多