File: lang-elixir.md

package info (click to toggle)
rust-wasmtime 26.0.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 48,492 kB
  • sloc: ansic: 4,003; sh: 561; javascript: 542; cpp: 254; asm: 175; ml: 96; makefile: 55
file content (43 lines) | stat: -rw-r--r-- 1,421 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Using WebAssembly from Elixir

Wasmtime [is available on Hex](https://hex.pm/packages/wasmex) and can
be used programmatically to interact with Wasm modules. This guide will go over
installing the wasmex package and running a simple Wasm module from Elixir.

## Getting started and simple example

First, copy this example WebAssembly text module into the current directory. It exports
a function for calculating the greatest common denominator of two numbers.

```wat
{{#include ../examples/gcd.wat}}
```

The library has a Rust-based native extension, but thanks to `rustler_precompiled`, you
should not have to compile anything. It'll just work!

This WAT file can be executed in `iex`:

```elixir
Mix.install([:wasmex])
bytes = File.read!("gcd.wat")
{:ok, pid} = Wasmex.start_link(%{bytes: bytes}) # starts a GenServer running a WASM instance
Wasmex.call_function(pid, "gcd", [27, 6])
```

The last command should output:

```elixir
iex(5)> Wasmex.call_function(pid, "gcd", [27, 6])
{:ok, [3]}
```

If this is the output you see, congrats! You've successfully ran your first
WebAssembly code in Elixir!

## More examples and contributing

To learn more, check out an [another example](https://github.com/tessi/wasmex#example)
and the [API documentation](https://hexdocs.pm/wasmex/Wasmex.html).
If you have any questions, do not hesitate to open an issue on the
[GitHub repository](https://github.com/tessi/wasmex).