fetch获取wasm模块实例
JavaScript代码
- /*** 完整的实例 ***/
- fetch("/pkg/wasm-lib/wasm_lib_bg.wasm")
- .then((response) => response.arrayBuffer())
- .then(bytes => {
- var module = new WebAssembly.Module(bytes);
- var imports = {
- "__wbindgen_init_externref_table": ()=> {}
- };
- var instance = new WebAssembly
- .Instance(module, { wbg: imports});
- console.log(instance.exports.add(1,2));
- })
axios获取wasm模块实例
JavaScript代码
- /*** 请求.wasm文件流 ***/
- this.$store.dispatch("test/getWasmStream",{}).then(async (res) => {
- WebAssembly.compile(res.data).then(module => {
- // 使用编译好的模块
- // 打印静态属性
- var imports = WebAssembly.Module.imports(module);
- var exports = WebAssembly.Module.exports(module);
- var strJSON = JSON.stringify({"imports":imports, "exports":exports}, null, 2)
- console.log('strJSON', strJSON)
- var imports = {
- "__wbindgen_init_externref_table": ()=> {}
- };
- /*** 使用WASM模块(运行实例) ***/
- var instance = new WebAssembly.Instance(module, {wbg: imports})
- //console.log(instance.exports.add(3,6))
- this.exports = instance.exports;
- }).catch(error => {
- console.error(error);
- });
- }).catch((error)=> {
- console.log('Action failed', error);
- });
loadWebAssemblyModule.js 封装
JavaScript代码
- /*
- * @Description: loadWebAssemblyModule.js
- * @Version: 1.0
- * @Author: Jesse Liu
- * @Date: 2022-11-14 10:32:06
- * @LastEditors: Jesse Liu
- * @LastEditTime: 2024-11-14 10:55:25
- */
- /*** AJAX加载WASM模块的函数 ***/
- const getWebAssemblyModule = (url) => {
- /*** 返回一个Promise ***/
- return new Promise(function(resolve, reject) {
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.responseType = 'arraybuffer';
- xhr.onload = function() {
- if (xhr.status === 200) {
- // 加载成功,编译WASM模块
- var arrayBuffer = xhr.response;
- WebAssembly.compile(arrayBuffer).then(function(module) {
- resolve(module);
- }).catch(function(error) {
- reject(error);
- });
- } else {
- // 出错了
- reject(new Error('Error loading WASM module: ' + xhr.statusText));
- }
- };
- xhr.send();
- });
- }
- /*** fetch加载WASM模块的函数 ***/
- const fetchWebAssemblyModule = (url) => {
- /*** 返回一个Promise ***/
- return new Promise(function(resolve, reject) {
- fetch(url)
- .then((response) => response.arrayBuffer())
- .then(bytes => {
- var module = new WebAssembly.Module(bytes);
- resolve(module);
- })
- .catch(error => {
- console.error('Fetch 错误:', error)
- reject(error);
- });
- });
- }
- export { fetchWebAssemblyModule, getWebAssemblyModule };