Skip to main content

Crate miniffi

Crate miniffi 

Source
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.rs is 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> or Rc<dyn T>)
  • Vec<T>
  • Option<T>
  • Box<T>

§Simple Usage

To get up and running:

  1. Add miniffi to your [build-dependencies] in Cargo.toml:

    cargo add --build miniffi
  2. Add the following code to the end of your src/lib.rs file:

    include!(concat!(env!("OUT_DIR"), "/miniffi.rs"));
  3. Add a build.rs script that calls build on at least one Target:

    use miniffi::*;
    
    fn main() {
        CppTarget::new().build();
    }
  4. 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§

BuildResult
Holds the result of calling build or build_custom. May print out cargo instructions and/or write files when dropped.
CppTarget
Use this target when the host language is C++.
FileData
Part of a BuildResult.
NullTarget
Use this target when there is no host language.
SwiftTarget
Use this target when the host language is Swift.
Warning
Part of a BuildResult.
WasmTarget
Use this target when the host language is JavaScript or TypeScript.

Traits§

Target
The common trait for all language-specific targets.