如何在wasm中生成导入节?

时间:2018-08-23 03:33:24

标签: webassembly

当我们将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实例时,应该如何自动导出那些部分?

1 个答案:

答案 0 :(得分:0)

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

为了执行,您需要设置一个合适的JavaScript环境来承载wasm模块。 Emscripten可以为您生成此信息:

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

上面的代码将生成一个hello.html文件,该文件带有关联的JavaScript代码,可让您执行模块。

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

  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