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

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)
    }
}
复制代码

 

posted @   Zhentiw  阅读(420)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示