0

I'm not sure why I can't find any good discussion of this, I have been searching since yesterday.

How do you return a class object from C++ binding and use its methods in Python i.e.:

class A {
    ...
    void foo() {
        py::print("Hello world");
    }
}

class B {
    ...
    A bar() {
        a = A();
        // What do I return here if I want to return a and use it in Python
        // return a
    }
}

I want to then bind B and use it in Python

b_object = B()
a = b_object.bar()
a.foo()

How do I do this in Pybind, Nanobind or Boost Python (if the syntax for the latter is similar).

I can't use lambdas when creating the B binding. The use case is actually more complex than what I've shown here.

2
  • Which part of this is giving you problems? Exporting classes is commonplace in examples and you shouldn't have issues finding inspiration there. Commented Feb 20, 2024 at 11:22
  • I think I have figured it out. Can I confirm that all I need to do is to add a binding for both classes in the PYBIND_MODULE and then I can just return the class as is? I couldn't find mention of this anywhere. Commented Feb 20, 2024 at 12:00

1 Answer 1

0

Can I confirm that all I need to do is to add a binding for both classes in the PYBIND_MODULE and then I can just return the class as is?

I believe this is true for nanobind, providing bindings for it registers it to be used as a type from Python. Additional bindings are necessary if you want more complex interactions (such as lists of A for example, will require it to be specified with bind_vector).

An example for completion:

#include <nanobind/nanobind.h>
namespace nb = nanobind;
#include <memory>

class A {
public:
    A(){};
    void foo() {
        nb::print("Hello world");
    }
};

class B {
public:
    B(){};
    A bar() {
        A a = A();
        return a;
    }
};

NB_MODULE(example, m) {
    nb::class_<A>(m, "A")
    .def(nb::init<>())
    .def("foo", &A::foo)
    ;
    nb::class_<B>(m, "B")
    .def(nb::init<>())
    .def("bar", &B::bar)
    ;
}

output:

>>> import example
>>> from example import *
>>> a = A()
>>> b = B()
>>> a.foo()
Hello world
>>> b.bar()
<example.A object at 0x7faa93f960d0>
>>> a = b.bar()
>>> a.foo()
Hello world
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.