乐闻世界logo
搜索文章和话题

How to call Rust from JS and back?

1个答案

1

The common approach to calling Rust from JavaScript and obtaining return values is by using WebAssembly (Wasm). WebAssembly enables running compiled code with near-native performance in almost all modern browsers, and Rust is one of the popular choices for generating WebAssembly code.

Operation Steps:

  1. Write Rust Code: First, create a Rust project and write the function you want to call from JavaScript.
  2. Compile to WebAssembly: Use wasm-pack, cargo-wasm, or other tools to compile your Rust code into a WebAssembly module.
  3. Integrate into JavaScript Project: In your JavaScript code, use the WebAssembly API to load the compiled .wasm file.
  4. Call Rust Functions: Once the WebAssembly module is loaded, you can call Rust functions as if they were regular JavaScript functions and obtain return values.

Below is a detailed step-by-step example:

Step 1: Write Rust Code

Assume we have a simple Rust function that calculates the sum of two numbers.

rust
// lib.rs use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(a: i32, b: i32) -> i32 { a + b }

Step 2: Compile to WebAssembly

In your Rust project directory, build the project using wasm-pack. If you haven't installed wasm-pack, download and install it from its official website.

sh
wasm-pack build --target web

This command generates a directory containing the .wasm file and a JavaScript script to facilitate loading the Wasm module.

Step 3: Integrate into JavaScript Project

Include the compiled Wasm code and the generated JavaScript script in your JavaScript project.

html
<!-- index.html --> <script type="module"> import init, { add } from './pkg/your_project_name.js'; async function run() { await init(); // Initialize the Wasm module const sum = add(2, 3); // Call the Rust function console.log(sum); // Output: 5 } run(); </script>

This example assumes the generated JS and Wasm files are located in './pkg/' and your project name is 'your_project_name'. The init function initializes the Wasm module, after which you can call the add function as if it were a regular JavaScript function.

Notes:

  • You need some background in Rust and JavaScript development.
  • Ensure that the Rust toolchain and wasm-bindgen are installed on your machine.
  • In some cases, additional configuration or optimization may be required for the generated Wasm and JavaScript code.
  • If your module is large or involves complex data types, you may need to use WebAssembly's memory and table APIs for more complex operations.
2024年6月29日 12:07 回复

你的答案