[Rust] Pass a JavaScript Function to WebAssembly and Invoke it from Rust

本文展示如何在Rust中调用JavaScript函数,通过将JavaScript函数传递给WebAssembly模块实例化过程。首先,在JavaScript中创建一个函数用于向页面body添加数字,然后将其封装在一个包含'env'的对象中。加载WebAssembly时,传入该对象。在Rust中创建一个外部函数,该函数在不安全的环境中调用JavaScript函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In some cases it’s useful to be able to invoke a JavaScript function inside Rust. This session showcases how this can be done, by passing along our JavaScript functions to the WebAssembly module instantiation.

 

First let's create a function in js:

      const appendNumberToBody = (number) => {
        const text = document.createTextNode(number);
        document.body.appendChild(text);
      }

 

Wrap this function into a single object which contains 'env':

      const importObject = {
        env: {
          appendNumberToBody: appendNumberToBody
        }
      };

 

When we load wasm, we can pass in the object:

WebAssembly.instantiateStreaming(fetch("utils.gc.wasm"), importObject)

It return a promise, we can run the exported function return by wasm inside the promise.

 

Now we are going to create a function in Rust:

extern {
    fn appendNumberToBody(x: u32);
}

#[no_mangle]
pub extern fn run() {
    unsafe { // we need to wrap with unsafe if getting the passed in value from third party
        appendNumberToBody(42);
    }
}

We exprot 'run' function, then we can invoke it inside promise:

      WebAssembly.instantiateStreaming(fetch("utils.gc.wasm"), importObject)
      .then(wasmModule => {
          wasmModule.instance.exports.run();
        });

 

---------

 

Full code: Github

index.html:

<!DOCTYPE html>
<html>
  <head>
    <script> 

      // pass the data from Js to Rust
      const appendNumberToBody = (number) => {
        const text = document.createTextNode(number);
        document.body.appendChild(text);
      }

      const importObject = {
        env: {
          appendNumberToBody: appendNumberToBody,
          alert: alert
        }
      };

      WebAssembly.instantiateStreaming(fetch("utils.gc.wasm"), importObject)
      .then(wasmModule => {
          wasmModule.instance.exports.run();
        });
    </script>
  <head>
  <body></body>
<html>

 

lib.rs:

extern {
    fn appendNumberToBody(x: u32);
    fn alert(x: u32);
}

#[no_mangle]
pub extern fn run() {
    unsafe {
        appendNumberToBody(42);
        alert(33)
    }
}

 

转载于:https://www.cnblogs.com/Answer1215/p/9823954.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值