The JS runtimes
Published in

The JS runtimes

Calling Rust functions from Deno — Part 1 Passing primitive types

Introduction

Basics

Imports

Permissions

Types

Native types =>    Void,
U8,
I8,
U16,
I16,
U32,
I32,
U64,
I64,
USize,
ISize,
F32,
F64,
Pointer

DlOpen

function dlopen (
filename: string,
symbols: S,
): DynamicLibrary<S>;
const dylib = Deno.dlopen('/var/lib/xyz.dylib', {
"print_something": { parameters: [], result: "void" },
"add": { parameters: ["u32", "u32"], result: "u32" },
});

Calling symbols

dylib.symbols.print_something();
dylib.symbols.add(123, 456);

Closing the library

dylib.close();

Steps to call Rust functions

Step 1: Write a Rust program

//lib.rsextern crate sysctl;
use sysctl::Sysctl;
#[no_mangle]
pub extern "C" fn get_hw_ncpu() -> i32 {
let v=sysctl::Ctl::new("hw.ncpu").unwrap().value().unwrap().to_string();
let r=v.parse::<i32>().unwrap();
return r;
}
#[no_mangle]
pub extern "C" fn get_hw_active_cpu() -> i32{
let v=sysctl::Ctl::new("hw.activecpu").unwrap().value().unwrap().to_string();
let r=v.parse::<i32>().unwrap();
return r;
}

Step 2: Write a build file

//Cargo.toml[package]
name = "deno_ffi_test"
version = "0.1.0"
publish = false
[lib]
crate-type = ["cdylib"]
[dependencies]
sysctl = "0.4.2"

Step 3: Build a shared library

denoFfiTest: cargo build
Compiling proc-macro2 v1.0.28
Compiling unicode-xid v0.2.2
Compiling syn v1.0.75
Compiling libc v0.2.100
Compiling byteorder v1.4.3
Compiling bitflags v1.3.2
Compiling quote v1.0.9
Compiling thiserror-impl v1.0.26
Compiling thiserror v1.0.26
Compiling sysctl v0.4.2
Compiling deno_ffi_test v0.1.0 (/Users/mayankc/Work/source/denoExamples/denoFfiTest)
Finished dev [unoptimized + debuginfo] target(s) in 8.86s
denoFfiTest: cargo clean
denoFfiTest: cargo build
Compiling proc-macro2 v1.0.28
Compiling unicode-xid v0.2.2
Compiling syn v1.0.75
Compiling libc v0.2.100
Compiling bitflags v1.3.2
Compiling byteorder v1.4.3
Compiling quote v1.0.9
Compiling thiserror-impl v1.0.26
Compiling thiserror v1.0.26
Compiling sysctl v0.4.2
Compiling deno_ffi_test v0.1.0 (/Users/mayankc/Work/source/denoExamples/denoFfiTest)
Finished dev [unoptimized + debuginfo] target(s) in 7.88s
denoFfiTest: ls target/debug/
build examples libdeno_ffi_test.d
deps incremental libdeno_ffi_test.dylib

Step 4: Open shared library in Deno

const libName = `denoFfiTest/target/debug/libdeno_ffi_test.dylib`;
const dylib = Deno.dlopen(libName, {
"get_hw_ncpu": { parameters: [], result: "i32" },
"get_hw_active_cpu": { parameters: [], result: "i32" }
});

Step 5: Calling the functions

dylib.symbols.get_hw_ncpu(); //8
dylib.symbols.get_hw_active_cpu(); //8

Step 6: Closing the library

dylib.close();

--

--

Articles on the popular JS runtimes, Node.js, Deno, and Bun

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store