Expand description
This is a simple but opinionated FFI system for Rust. It allows you to call Rust code from other languages, and vice versa. Some design principles:
- Intended for writing platform-agnostic Rust with platform-specific details in the host language
- FFI support is split into data (structs passed by copy) and code (traits passed by reference)
- Rather than have a separate schema language, the public API in your
lib.rsis your schema - The generated binding code is compact, dependency-free, and straightforward to integrate with
§Supported Features
- Primitive types (
bool,i32,f64,String, etc.) - Tuples
- Structs
- Enums
- Top-level constants
- Top-level functions
- Traits (must be either
Box<dyn T>orRc<dyn T>) Vec<T>Option<T>Box<T>
§Simple Usage
To get up and running:
-
Add
miniffito your[build-dependencies]inCargo.toml:cargo add --build miniffi -
Add the following code to the end of your
src/lib.rsfile:include!(concat!(env!("OUT_DIR"), "/miniffi.rs")); -
Add a
build.rsscript that callsbuildon at least oneTarget:use miniffi::*; fn main() { CppTarget::new().build(); } -
Import the generated bindings from the host language (see each target for details)
§Advanced Usage
You can only build for one target at a time. However, the flexibility of build scripts means you can use the same build script for different targets in different situations using your own custom logic.
For example, you may want to build for different host languages depending
on the value of cargo’s --target flag:
use miniffi::*;
fn main() {
let target = std::env::var("TARGET").unwrap();
if target == "wasm32-unknown-unknown" {
WasmTarget::new()
.write_ts_to("../web/rust.ts")
.set_panic_hook()
.build();
} else if target == "aarch64-apple-darwin" {
SwiftTarget::new()
.write_swift_to("../macos/rust.swift")
.write_header_to("../macos/rust.h")
.build();
} else if target == "x86_64-pc-windows-msvc" {
CppTarget::new()
.write_source_to("../windows/rust.cpp")
.write_header_to("../windows/rust.h")
.build();
} else {
NullTarget::new().build();
}
}Structs§
- Build
Result - Holds the result of calling
buildorbuild_custom. May print out cargo instructions and/or write files when dropped. - CppTarget
- Use this target when the host language is C++.
- File
Data - Part of a
BuildResult. - Null
Target - Use this target when there is no host language.
- Swift
Target - Use this target when the host language is Swift.
- Warning
- Part of a
BuildResult. - Wasm
Target - Use this target when the host language is JavaScript or TypeScript.
Traits§
- Target
- The common trait for all language-specific targets.