How to get instance of sub/child class at runtime? #81
-
If I have a method which returns a pointer to parent type, it looks like with pybind, I can use the actual runtime (parent or child) type for methods/functions on that instance. OTOH, in nanobind, probably because there is no holder pointer, but an instance of the type in the python object, I can't use the runtime-specific methods/functions on the instance. Is there a way to work around this in general ? Or do I have to make sure that all functions return the actual type, which would mean that I'd have to know ahead of time what type to expect (in python) ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
One way I could imagine this is to check for the type inside a wrapper function, have that wrapper function return a Does this make sense ? Is there an easier way to do this automatically? |
Beta Was this translation helpful? Give feedback.
-
So imagine we have this structure in C++ and we want to wrap the functions struct Parent { ... };
struct Child : struct Parent { ... };
Parent* make_parent(bool child) {
if (child)
return new Child();
return new Parent();
}
void print_stuff(Parent& p) { printf("this is a parent\n"); }
void print_stuff(Child& c) { printf("this is a parent\n"); } If we bind those classes and functions in a straightforward way using nanobind, then call |
Beta Was this translation helpful? Give feedback.
So imagine we have this structure in C++ and we want to wrap the functions
make_parent
andprint_stuff
overloads:If we bind those classes and functions in a straightforward way using nanobind, then call
make_parent(True)
from python, and then callprint_stuff
on the result, we'll get "this is a parent".In pybind, we would get "this is a child" AFAIU