Search code examples
swiftrustswiftuiipcdesktop-application

How to communicate data between programming languages?


I am thinking starting a new project (Desktop application). Performance is a must and I need fast and reliable languages like Rust. In the other hand, I want to use native UI toolkits given by the OS like SwiftUI.

I did some research about it and didn't find anything concrete.

  • I insist in using Rust and Swift, no other languages.
  • Local API and opening ports is not an option.
  • Writing to file then reading from it using the other language could be an option, but I don't think doing this is good practice and efficient.
  • Using a sort of an inter-process communication is a good solution. But I have no clue how to do it, especially between two different languages. If someone could explain it or have some references of how it works in details to implement it from scratch.

To sum up, I want to use SwiftUI as frontend, and Rust as backend with highest speed data communication and lowest latency. What's the best way to do it?

NB: Perhaps some of the solutions above make no sense. Correct me if some of them are wrong.


Solution

  • I don't know Swift by I have done some IPC with C++/C# in the past.

    If you want "highest speed data communication and lowest latency" there is no option but C FFI. This is very fast because all code would be in one process and you would be able to share memory very easily without any copying.

    I don't know about Swift but Rust code can provide C API which allows to be called from any other language which supports C FFI. You can link you Rust code dynamically (by building DLL/.so by setting crate type to cdylib) or statically (by setting crate type to staticlib). You may read more about FFI here: https://doc.rust-lang.org/nomicon/ffi.html

    If you don't really need "highest speed data communication and lowest latency" (you may because you ever considered files as option), you may consider using 2 different processes which interoperate using OS level mechanisms. Most common way to do this is pipes:

    You may try to use this crate for this: https://crates.io/crates/os_pipe

    Also, on Unix you can use unix domain sockets for that. This is very similar to network sockets but much faster.