Here’s an example showing how to call a Rust function from Deno:

    Compile it to a C dynamic library (libadd.so on Linux):

    1. rustc --crate-type cdylib add.rs

    In C you can write it as:

    1. // add.c
    2. int add(int a, int b) {
    3. return a + b;
    4. }

    And compile it:

    Calling the library from Deno:

    1. // ffi.ts
    2. // Determine library extension based on
    3. // your OS.
    4. let libSuffix = "";
    5. switch (Deno.build.os) {
    6. case "windows":
    7. libSuffix = "dll";
    8. case "darwin":
    9. libSuffix = "dylib";
    10. break;
    11. case "linux":
    12. libSuffix = "so";
    13. break;
    14. }
    15. const libName = `./libadd.${libSuffix}`;
    16. // Open library and define exported symbols
    17. const dylib = Deno.dlopen(libName, {
    18. "add": { parameters: ["isize", "isize"], result: "isize" },
    19. });
    20. // Call the symbol `add`
    21. const result = dylib.symbols.add(35, 34); // 69
    1. deno run --allow-ffi --unstable ffi.ts

    There are many use cases where users might want to run CPU-bound FFI functions in the background without blocking other tasks on the main thread.

    As of Deno 1.15, symbols can be marked nonblocking in Deno.dlopen. These function calls will run on a dedicated blocking thread and will return a Promise resolving to the desired result.

    Example of executing expensive FFI calls with Deno:

    Calling it from Deno:

    1. // nonblocking_ffi.ts
    2. const library = Deno.dlopen("./sleep.so", {
    3. sleep: {
    4. parameters: ["usize"],
    5. result: "void",
    6. nonblocking: true,
    7. },
    8. });
    9. library.symbols.sleep(500).then(() => console.log("After"));
    10. console.log("Before");

    Result:

    1. $ deno run --allow-ffi --unstable unblocking_ffi.ts
    2. Before
    3. After
    • [1] pointer type accepts both Typed Arrays and Deno.UnsafePointer as parameter, while it always returns the latter when used as result type.

    is an external tool to simplify glue code generation of Deno FFI libraries written in Rust.

    It is similar to wasm-bindgen in the Rust WASM ecosystem.

    Here’s an example showing its usage:

    Run deno_bindgen to generate bindings. You can now directly import them into Deno:

    1. // mul.ts
    2. mul({ a: 10, b: 2 }); // 20

    Any issues related to deno_bindgen should be reported at