swift icon indicating copy to clipboard operation
swift copied to clipboard

[cxx-interop] Support inheriting C++ classes in Swift

Open mrousavy opened this issue 1 year ago • 0 comments

Motivation

I'm building a framework where people can build modules using Swift. Those modules are then exposed to JavaScript, using a C++ based interface.

For example, if a developer wants to implement an Image editing module, I would generate a C++ specification (based off of some information the developer gives me) like so:

class Image {
public:
  virtual int getWidth() = 0;
  virtual int getHeight() = 0;
};

Now I want developers to be able to extend Image using Swift classes, so something like this:

class ImageImpl : Image {
  var width: Int { return 100 }
  var height: Int { return 100 }
}

I am not a compiler engineer nor do I understand the memory layout differences between Swift and C++ classes, so I am not even sure if it is possible to mix those classes together. That's why I'm raising this enhancement idea as a place for discussion.

Proposed solution

It would be cool if abstract/virtual C++ classes could be extended in Swift.

Maybe via a common protocol (but then downcasting should work), or just via a Swift class.

Either way, I want to use Image (not ImageImpl) in C++ and have it use the virtual/overridden implementation from ImageImpl.

Alternatives considered

I currently didn't find any alternatives other than hardcoding both classes and nesting the instances as members.

Additional information

No response

mrousavy avatar Jul 17 '24 15:07 mrousavy