gpt4 book ai didi

webassembly - 如何在 wasm 中生成导入部分?

转载 作者:行者123 更新时间:2023-12-05 07:31:02 25 4
gpt4 key购买 nike

当我们将一个c源文件编译成wasm时,会有很多import "env"xxxx段。比如这是我的c源文件,

char message[] = "hello wasm!";
char* getMessageRef() {
return message;
}
int getMessageLength() {
return sizeof(message);
}

const int SIZE = 10;
int data[SIZE];

void add(int value) {
for (int i=0; i<SIZE; i++) {
data[i] = data[i] + value;
}
}

int* getData() {
return &data[0];
}

编译后会生成相关的wat文件

(module
(type (;0;) (func (param i32 i32 i32) (result i32)))
(type (;1;) (func (param i32) (result i32)))
(type (;2;) (func (result i32)))
(type (;3;) (func (param i32)))
(type (;4;) (func (param i32 i32) (result i32)))
(type (;5;) (func (param i32 i32)))
(type (;6;) (func))
(type (;7;) (func (param i32 i32 i32 i32) (result i32)))
(import "env" "memory" (memory (;0;) 256 256))
(import "env" "table" (table (;0;) 10 10 anyfunc))
(import "env" "memoryBase" (global (;0;) i32))
(import "env" "tableBase" (global (;1;) i32))
(import "env" "DYNAMICTOP_PTR" (global (;2;) i32))
(import "env" "tempDoublePtr" (global (;3;) i32))
(import "env" "ABORT" (global (;4;) i32))
(import "env" "STACKTOP" (global (;5;) i32))
(import "env" "STACK_MAX" (global (;6;) i32))
(import "global" "NaN" (global (;7;) f64))
(import "global" "Infinity" (global (;8;) f64))
(import "env" "enlargeMemory" (func (;0;) (type 2)))
(import "env" "getTotalMemory" (func (;1;) (type 2)))
(import "env" "abortOnCannotGrowMemory" (func (;2;) (type 2)))
(import "env" "abortStackOverflow" (func (;3;) (type 3)))
(import "env" "nullFunc_ii" (func (;4;) (type 3)))
(import "env" "nullFunc_iiii" (func (;5;) (type 3)))
(import "env" "___lock" (func (;6;) (type 3)))
(import "env" "___setErrNo" (func (;7;) (type 3)))
(import "env" "___syscall140" (func (;8;) (type 4)))
(import "env" "___syscall146" (func (;9;) (type 4)))
(import "env" "___syscall54" (func (;10;) (type 4)))
(import "env" "___syscall6" (func (;11;) (type 4)))
(import "env" "___unlock" (func (;12;) (type 3)))
(import "env" "_emscripten_memcpy_big" (func (;13;) (type 0)))
(func (;14;) (type 1) (param i32) (result i32)
... omit plenty of lines

那么在实例化 wasm 实例时应该如何自动导出这些部分呢?

最佳答案

当使用 Emscripten 编译 C/C++ 文件时,它会在生成的 wasm 输出中添加一个轻量级的运行时,这就是为什么你会看到这些不同的导入。

为了执行,您需要设置合适的 JavaScript 环境来托管 wasm 模块。 Emscripten 可以为您生成这个:

./emcc tests/hello_world.c -o hello.html

上面的代码将生成一个 hello.html 文件,其中包含相关的 JavaScript 代码,您可以使用它来执行您的模块。

对于简单的应用程序,您可能可以自己创建 require 环境。这是一个例子:

  const imports = {
env: {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({
initial: 512
}),
table: new WebAssembly.Table({
initial: 0,
element: 'anyfunc'
})
}
};

const instance = new WebAssembly.Instance(module, imports);

这是来自 example I wrote使用 C/Emscripten 创建 Mandelbrot

关于webassembly - 如何在 wasm 中生成导入部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51977970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com