matusnovak / wrenbind17

A header only library for binding C++17 classes and functions to Wren, an embeddable programming language
https://matusnovak.github.io/wrenbind17
MIT License
65 stars 10 forks source link

Derived class returned as a base class from C++ cannot use derived methods #4

Closed germandiagogomez closed 3 years ago

germandiagogomez commented 3 years ago

Hello.

I have been using ChaiScript and I am migrating to Wren because of the fibers stuff that I need badly :)

First, thanks a lot for this project, it is making things much easier so far. I would like to point out one thing that worked in ChaiScript but does not in wrenbind17 that is related to inheritance.

I have registered the base class with its methods and the derived class with all methods, derived and base. I am using module.klass<derived, base>("derived") and registering the funcs I want.

So, let us say I have derived::derivedMethod in C++. The following will not work

// C++ code
shared_ptr<BaseClass> BaseClass::factory(std::string_view className) {
          return some_derived_class_from_base_class;
}

//wren code
_myInstance =  BaseClass.factory("derived")
_myInstance.derivedMethod()

Factory is returning a base class shared pointer but the real instance held is of type derived. In ChaiScript the derived methods will work, but in WrenBind17 the following error is shown:

exception: Runtime error: base does not implement 'derivedMethod()'

Any workaround? Could this be implemented in some way? Maybe I could help, but not sure how much time I will have available. Depends on difficulty. Thanks!

matusnovak commented 3 years ago

Hi @germandiagogomez I am currently busy but I will look at this soon.

matusnovak commented 3 years ago

Hi @germandiagogomez

The module.klass<derived, base>("derived") is used to do upcasting -> https://matusnovak.github.io/wrenbind17/tutorial/custom_types/#66-upcasting This won't solve your problem with calling derived methods.

In order to do that, you will have to:

Essentially, use polymorphism.

I have added a test that shows this functionality, here: https://github.com/matusnovak/wrenbind17/commit/367bcaba8a772dbe2190f49ff410e4f6cc1d0ed0 Is this what you are looking for?

Automatically inheriting all registered functions from the base class(es) into the derived class is something I would like to implement at some point, but I would like to have it optional. The only problem that keeps me from doing that is that in Wren language you can only inherit from one class at the time [citation needed]. So when you have a C++ class that inherits from multiple classes it gets a little bit tricky.

germandiagogomez commented 3 years ago

Yes, that is exactly what I was looking for. I will close this issue. Thanks!