Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support inheriting from C++ classes in Rust #7

Open
anderslanglands opened this issue Sep 17, 2022 · 0 comments
Open

Support inheriting from C++ classes in Rust #7

anderslanglands opened this issue Sep 17, 2022 · 0 comments

Comments

@anderslanglands
Copy link
Contributor

!WIP - this is just a scratchpad, not fully thought through yet.

This would require:

  • Tagging ClassDecls as being a base class after parsing, and tagging each non-pure, non-final method to be overriden
  • During writing, given a C++ base class Base, generating:
    • A C++ class, BaseEx that inherites from Base and provides overrides for each of the tagged methods, as well as any pure virtual ones. Each constructor of BaseEx should be modified to take a "subclass" pointer as its first argument, which will be stashed as a field.
    • A matching C ABI function for each overriden method in in BaseEx, taking a void* subclass as its first argument
    • C translations (using the normal mechanism) of each constructor of BaseEx
    • The implementation of BaseEx just forwards to the matching C versions of its methods

... then on the Rust side the void sublcass* is used to take a Box<Box<dyn BaseEx>>

// original c++
class Base {
    virtual void do_thing(int a);
};

// generated c++
extern int fwd_BaseEx_do_thing(void* _subclass, int a); // defined in Rust

class BaseEx {
    void* _subclass;
public:
    BaseEx(void* subclass) : _subclass(subclass){}
    void do_thing(int a) override { fwd_BaseEx_do_thing(_subclass, a); }
};

void BaseEx_ctor(void* subclass, BaseEx** result) {
    *result = new BaseEx(subclass);
}
#[no_mangle]
extern "C" fn fwd_BaseEx_do_thing(subclass: *mut c_void, a: c_int) {
    let base_ex = std::mem::transmute::<*mut c_void, Box<Box<dyn BaseEx>>(subclass);
    base_ex.do_thing(a);
}

trait BaseEx {
    fn get_subclass(&self) -> &Box<Box<dyn BaseEx>>;
}

// todo: ownership on the Rust side for trait impls?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant