Calling a Rust program using Wasm

aryank21

Aryan Kaushik

Posted on April 28, 2022

Calling a Rust program using Wasm

Hi Folks, Welcome to another Blog. Today, we'll learn about how to call a rust program using Wasm.
Getting Started:

1. We need rust and wasm-pack in our system, lets install them:

a. For Rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Enter fullscreen mode Exit fullscreen mode

b. For wasm-pack

cargo install wasm-pack
Enter fullscreen mode Exit fullscreen mode

1

2

Cargo is a Rust package manager. Cargo downloads your Rust package's dependencies, compiles your packages, makes distributable packages, and uploads them to crates.io, the Rust community's package registry.

2. Create a Library, here I've named it

"ary-kaush"

cargo new --lib ary-kaush
Enter fullscreen mode Exit fullscreen mode

3

3. Move to the library,

cd ary-kaush/

4

and open vs code by using code . command.

we can see that there is a folder named src and a file named cargo.toml.

z

4. In order to create a wasm module, we need to specify the type of package.

For adding such specification we need to modify Cargo.toml file. By adding:
a. crate type:

[lib]
crate-type = ["cdylib"]
Enter fullscreen mode Exit fullscreen mode

b. dependancies:

wasm-bindgen = "0.2.78"
Enter fullscreen mode Exit fullscreen mode

x

5. Change default code in src/lib.rs to the code that we wan't to run

here we are making a function to add two numbers.

5

6. Now building the package

wasm-pack build
Enter fullscreen mode Exit fullscreen mode

6

after build, a lot of files has been created to support the package.

7. In order to run this program, run:

wasm-pack build --target nodjs
Enter fullscreen mode Exit fullscreen mode

Image description

A pkg folder will be created which includes .wasm,.ts, js and .json files.

8. To run our program we need to create a index.js file and where we will make a math library.

const math  = require('./ary_kaush.js')

console.log(math.add2numbers(10,20));
Enter fullscreen mode Exit fullscreen mode

In VScode
8.1

9. move in pkg by cd pkg/ and run

node index.js
Enter fullscreen mode Exit fullscreen mode

8

and Finally we have the required output.

Image description

This was a basic program in rust, whereas we can create multiple projects e.g. a calculator, fibonacci series, to find whether the number is prime or not etc. .

Please check out blog by @moksh_pathak , where he created a calculator using Rust and ran it in Enarx.

Stay tuned for more stuff!

Do comment your ideas and suggestions related to the blog and please share if you found it useful.
Write your queries in comment section, we'll help you to resolve your errors.

💖 💪 🙅 🚩
aryank21
Aryan Kaushik

Posted on April 28, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Calling a Rust program using Wasm
beginners Calling a Rust program using Wasm

April 28, 2022