Alexander Soare
Alexander Soare

Reputation: 3267

Return a 3rd party pybind type

My C++ library depends on a 3rd party C++ library with its own bindings.

I bind a struct that uses def_readwrite to expose its members. One of its members is a type from the 3rd party library.

Basically I have:

struct MyStruct {
  ClassFromThirdParty member{};
}

py::class_<MyStruct>(m, "MyStruct")
    .def_readwrite("member", &MyStruct::member)

In Python I try:

from my_bindings import MyStruct

obj = MyStruct()
print(obj.member)

but this raises TypeError: Unable to convert function return value to a Python type!.

It's worth also noting that if I do:

import ThirdPartyLibrary
from my_bindings import MyStruct

obj = MyStruct()
print(obj.member)

no error is raised. But I don't like this solution as the Python user would have to import ThirdPartyLibrary even if they don't explicitly need it.

How do I write my binding such that the first Python snippet works?

PS: The third party binding in question can be found here. In the absence of a general answer, I'd also be happy to hear answers related to that library in particular.

Upvotes: 0

Views: 471

Answers (1)

jwnimmer-tri
jwnimmer-tri

Reputation: 2464

It's the same in pybind11 as it is in Python -- you need to import classes before you can rely on them.

Add py::module::import("pydrake.math"); to your PYBIND11_MODULE before trying to define function bindings that operate on a pydrake.math.RigidTransform as a C++ argument type or C++ return value type.

Upvotes: 2

Related Questions