pybind11中的动态返回类型的功能
在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该解决方案,借助 @osyotr的评论非常简单:
pybind11会自动照顾将
variant
的正确组件发送到python side。The solution, thanks to @Osyotr's comment, is very simple:
PyBind11 takes automatically care of providing the right component of the
variant
to the Python side.