pybind11中的动态返回类型的功能

发布于 2025-02-12 12:40:54 字数 438 浏览 1 评论 0原文

在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

这根本可能吗?

In python you can define functions which dynamically return different types:

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

How can I implement in C++ a function like this and export it with pybind11?

Ideally it would be something like:

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

However, I did not find how to construct py::object using objects of registered C++ types.

Is this possible at all?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木槿暧夏七纪年 2025-02-19 12:40:54

该解决方案,借助 @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会自动照顾将variant的正确组件发送到python side。

The solution, thanks to @Osyotr's comment, is very simple:

#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 takes automatically care of providing the right component of the variant to the Python side.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文