Replies: 2 comments 1 reply
-
I don't see a problem in general, can you be more specific with description or give some reproducer of your case? Try this sample: #include <variant>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
class TestClass
{
public:
TestClass(int value) : m_value(value) {}
int get_value()
{
return m_value;
}
private:
int m_value;
};
PYBIND11_MODULE(mymodule, m)
{
py::class_<TestClass, std::shared_ptr<TestClass>> cls(m, "TestClass");
cls.def(py::init<int>());
cls.def("get_value", &TestClass::get_value);
m.def("foo", [](bool flag)
{
std::variant<int, TestClass> value;
if (flag)
{
value = TestClass(13);
}
else
{
value = 42;
}
return value;
});
} In Python it works like a charm, no need to cast it. Returned type is already correct. In [1]: import mymodule
In [2]: x = mymodule.foo(False)
In [3]: x
Out[3]: 42
In [4]: x = mymodule.foo(True)
In [5]: x
Out[5]: <mymodule.TestClass at 0x1031d9e70>
In [6]: type(mymodule.foo(False)) == int
Out[6]: True
In [7]: type(mymodule.foo(False)) == float
Out[7]: False
In [8]: type(mymodule.foo(True)) == int
Out[8]: False
In [9]: type(mymodule.foo(True)) == mymodule.TestClass
Out[9]: True |
Beta Was this translation helpful? Give feedback.
0 replies
-
It seems it was my mistake and I get it work now. Sorry for bothering. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I see there is a support for
std::variant
-like types in pybind11, and variant types can be passed as arguments and return values of C++ functions. However, there seems no way to check a variant type in Python side.It would be better if I can use a variant type like this:
Beta Was this translation helpful? Give feedback.
All reactions