29

I'd like to be able to use Rust objects in Swift, somehow notify Swift when Rust objects change/events happen, and leverage Swift's ARC to keep Rust objects alive.

So far what comes to my mind is to write a plain C API for the Rust objects, then write an Objective-C wrapper for the C API, and then export that to Swift, like this:

adapting adapters

Is there a less tedious way? Something that can automatically generate wrapper functions and C header files?

Kornel
  • 97,764
  • 37
  • 219
  • 309

1 Answers1

8

I am working on a project similar to this right now (porting a C++ library to function on both iOS and Android).

The only sane way to do this is to extern "C" your Rust interfaces and write a simple .h file for it, and create a simple ObjC class wrapping for those. You then pop the #import <someframework/someframework.h> into the Objective C to Swift binding header and it all just works.

It's a bit tedious but it's really not all that much work in practice. It only gets painful if you try to transfer complex objects across boundaries, which results in writing a bunch of structs, and then everything goes downhill. I advise you against that, stick to primitives and arrays.

If your model is more complex than that, consider something like IPC as others have said, though that might be much more painful in practice.

So yep, tedious. The good news though is that this actually does work, though. :)

Brendan Molloy
  • 1,784
  • 14
  • 22