Skip to content

Support inheriting from C++ classes in Rust #7

@anderslanglands

Description

@anderslanglands

!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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions