Swift dylib in Rust without using unsafe

91 Views Asked by At

Is there is any way to run Swift dylib from Rust without using unsafe? Or is there any way to call the Swift functions from Rust without Rust's unsafe? To date whatever I tried I had to use unsafe.

2

There are 2 best solutions below

1
Aleksander Krauze On

No. It is impossible to call any external (FFI) functions from Rust without specifying them as unsafe. You have to assert to the compiler that this code upholds all rust safety requirements. And since compiler cannot do that, you have to do it manually by using unsafe (and of course it has to be safe to do it).

To better understand why there is unsafe in the language read chapter on Unsafe Rust from the Rust Programming Language, and especially Using extern functions to call external code paragraph.

1
Caesar On

@AleksanderKrauze is technically correct. Somewhere, there needs to be unsafe code for the FFI. But that doesn't mean that you need to write that unsafe code yourself.
You could for example use something that generates that unsafe code for you. If that something is well-made (i.e. sound), all the code you write will be safe rust, and you won't need to worry about accidental undefined behavior.

swift-bridge might be one such something, but I can't vouch for its completeness or soundness.