Code Monkey home page Code Monkey logo

membrane's Introduction

Membrane

Membrane is an opinionated crate that generates a Dart package from your Rust library. It provides extremely fast performance with strict typing, automatic memory management, and zero copy returns over the FFI boundary via bincode.

Membrane diagram

Development Environment

On Linux ffigen looks for libclang at /usr/lib/llvm-11/lib/libclang.so so you may need to symlink to the version specific library: ln -s /usr/lib/llvm-11/lib/libclang.so.1 /usr/lib/llvm-11/lib/libclang.so.

On MacOS M1, ffigen still uses llvm for x86 architecture so far, while M1 is arm64: you might get an error mentioning incompatible architecture (have 'arm64', need 'x86_64').

click & follow steps

Essentially, you will need to install x86_64 variants of tools. Grab a coffee, this might take a while ☕

  • Rosetta2 (optional, only if asked)
  • Rust toolchain
    rustup target add x86_64-apple-darwin
  • brew
    arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
  • llvm
    arch -x86_64 /usr/local/bin/brew install llvm
    ⚠️ if asked to install additional packages, just follow recommendations in the console, e.g. :
    arch -x86_64 /usr/local/bin/brew install [email protected]
  • ffi
    arch -x86_64 sudo gem install ffi
  • finally run!
    # MEMBRANE_LLVM_PATHS must be set to folder's path
    # where llvm for x86_64 is installed
    export MEMBRANE_LLVM_PATHS=/usr/local/opt/llvm && cargo run --target=x86_64-apple-darwin

Usage

View the example directory for a runnable example.

In your crate's lib.rs add a RUNTIME static that will survive for the lifetime of the program. RUNTIME must provide a spawn function, in this case we're using tokio:

use once_cell::sync::Lazy;
use tokio::runtime::{Builder, Runtime};

pub(crate) static RUNTIME: Lazy<Runtime> = Lazy::new(|| {
  Builder::new_multi_thread()
    .worker_threads(2)
    .thread_name("libexample")
    .build()
    .unwrap()
});

Then write some code that is annotated with the #[async_dart] macro. No need to use C types here, just use Rust String, i64, f64, bool, structs, or enums as usual (or with Option). The functions can be anywhere in your program and may return either an async Result<T, E> or an impl Stream<Item = Result<T, E>>:

use membrane::async_dart;
use tokio_stream::Stream;

use crate::data;

#[async_dart(namespace = "accounts")]
pub fn contacts() -> impl Stream<Item = Result<data::Contact, data::Error>> {
  futures::stream::iter(vec![Ok(Default::default())])
}

#[async_dart(namespace = "accounts")]
pub async fn contact(id: String) -> Result<data::Contact, data::Error> {
  Ok(data::Contact {
    id: id.parse().unwrap(),
    ..Default::default()
  })
}

And now you are ready to generate the Dart package. Note that this code goes in a bin/generator.rs or similar to be ran with cargo run or a build task rather than in build.rs (which only runs before compilation):

fn main() {
  // if nothing else in this generator.rs references lib.rs then
  // at least call a dummy function so lib.rs doesn't get optimized away
  example::load();

  let mut project = membrane::Membrane::new();
  project
    // name the output pub directory
    .package_destination_dir("../dart_example")
    // the pub package name, if different than the directory
    .package_name("example")
    // give the basename of the .so or .dylib that your Rust program provides
    .using_lib("libexample")
    // use Dart enums instead of class enums
    .with_c_style_enums(true)
    .create_pub_package()
    .write_api()
    .write_c_headers()
    .write_bindings();
}

If everything went as planned you can now call Rust from Dart with:

cd example
cargo run
cargo build
cd ../dart_example
cp ../example/target/debug/libexample.dylib .
dart --enable-asserts run

(--enable-asserts enables a pretty print toString() in the generated classes)

import 'package:dart_example/accounts.dart';

void main(List<String> arguments) async {
  var accounts = AccountsApi();
  print(await accounts.contact(id: "1"));
}

If you get an error on Linux about not being able to load libexample.so then add the pub package's path to LD_LIBRARY_PATH.

membrane's People

Contributors

jerel avatar kturney avatar roms1383 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.