Expand description
Compiles a Mac app’s Swift code from build.rs and links it into the
app, so Rust can call Swift (and SwiftUI) through @_cdecl functions.
// build.rs
fn main() {
ferrokit_build::swift("swift").compile();
}# Cargo.toml
[build-dependencies]
ferrokit-build = "0.15"Every .swift file under the folder (here swift/, next to
Cargo.toml) is compiled by swiftc into one static library, which is
linked into the package’s binaries. The Swift runtime, SwiftUI and the
rest of Apple’s frameworks come with macOS, so nothing is copied into the
app; the frameworks the Swift code imports are linked automatically.
swiftc comes with the Command Line Tools (xcode-select --install),
which a Rust build on a Mac needs anyway. SwiftUI’s macros (@State,
@Entry, #Preview: macros since the macOS 27 SDK) need Xcode, whose
plugin expands them: when the Command Line Tools are selected and an
Xcode is in /Applications, it’s used for the Swift (with a warning).
Setting DEVELOPER_DIR picks the toolchain yourself, and turns that
fallback off.
On the Swift side, export functions with C names; on the Rust side,
declare them in an extern "C" block:
// swift/Greeting.swift
@_cdecl("greeting_length")
public func greetingLength(_ name: UnsafePointer<CChar>) -> Int {
"Hello, \(String(cString: name))!".count
}unsafe extern "C" {
fn greeting_length(name: *const std::ffi::c_char) -> isize;
}
// SAFETY: a NUL-terminated string.
let n = unsafe { greeting_length(c"Ferrokit".as_ptr()) };A SwiftUI view goes into a Ferrokit window through ferrokit::native: a
Swift function returns an NSHostingView (Unmanaged.passRetained(view) .toOpaque()), and native(|_| unsafe { Retained::from_raw(ptr.cast()) } .unwrap()) wraps it. Ferrokit’s guide, chapter 14, has the whole recipe.
The settings follow the build: the target’s architecture (so universal
builds work), optimisation and debug info from the Cargo profile, and the
minimum macOS from MACOSX_DEPLOYMENT_TARGET, else 15.0.
Put the Swift code in the package that builds the app (its binary or example): the link settings Cargo passes from a build script reach that package’s own binaries only.
Structs§
Enums§
- Error
- Why the Swift code couldn’t be compiled.