問題描述
如何在 Webassembly 中獲取 JSON 文件 (How to Fetch a JSON file in Webassembly)
Imports 參數必須存在並且必須是 fetch.then.then.then.module (wasmbyfile.js:64) 處的對象</p>
方法 2:
#include <stdio.h>
include <string.h>
include <emscripten/fetch.h>
/////////////////////////
// This file contains the code for fetching
// ‑> Compiled to .wasm file with emscripten <‑////////////////////////
void downloadSucceeded(emscripten_fetch_t *fetch) {
printf("Finished downloading %llu bytes from URL %s.\n", fetch‑>numBytes, fetch‑>url);
// The data is now available at fetch‑>data[0] through fetch‑>data[fetch‑>numBytes‑1];
emscripten_fetch_close(fetch); // Free data associated with the fetch.
}
void downloadFailed(emscripten_fetch_t *fetch) {
printf("Downloading %s failed, HTTP failure status code: %d.\n", fetch‑>url, fetch‑>status);
emscripten_fetch_close(fetch); // Also free data on failure.
}
int main() {
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY | EMSCRIPTEN_FETCH_PERSIST_FILE;
attr.onsuccess = downloadSucceeded;
attr.onerror = downloadFailed;
emscripten_fetch(&attr, "./json/bol_list1.json");
}
</code></pre>
錯誤結果:未捕獲(在承諾中)TypeError:WebAssembly 實例化:Imports 參數必須存在並且必須是一個對象
所以我被困在這一點上,並且不確定如何在 JS 中正確加載模塊。我需要一些幫助,還是我從一開始就以錯誤的方式做這件事,有沒有更好的方法來做這件事?
並且不確定如何在 JS 中正確加載模塊。我需要一些幫助,還是我從一開始就以錯誤的方式做這件事,有沒有更好的方法來做這件事?</p> 並且不確定如何在 JS 中正確加載模塊。我需要一些幫助,還是我從一開始就以錯誤的方式做這件事,有沒有更好的方法來做這件事?</p>
參考解法
方法 1:
You are getting an error because your WASM has import statements, while your call to instantiateStreaming does not send an importObject.
But the basic way to use WASM from Javascript is much simpler than: Just define a function in WASM that you can call from JS, and then you do the "fetch" from JS, for instance ("add.wasm"):
(module
(type $t0 (func (param i32 i32) (result i32)))
(func $add (type $t0) (param $p0 i32) (param $p1 i32) (result i32)
get_local $p0
get_local $p1
i32.add)
(export "add" (func $add)))
And then call it from Javascript:
const wasmInstanceFromFile = await WebAssembly.instantiateStreaming(await fetch('add.wasm'));
let sum = wasmInstanceFromFile.instance.exports.add(1,2);
參考文件