You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向WebAssembly传递数据失败求助:JS传值至WASM未生效

Why Isn't My WebAssembly Module Picking Up the Global Variable from JavaScript?

Let's break down why your code returns 0 instead of 5, and fix it step by step:

1. The Core Problem

When you write extern int x; in C, the WebAssembly compiler needs clear instruction that this variable should be imported from the JavaScript host—it won't automatically infer this. Additionally, you can't pass raw numeric values directly as imported globals; WebAssembly expects a properly typed WebAssembly.Global instance, not an immediate number.

2. Fix the C Code

You need to explicitly mark the x variable as an imported value. If you're using Clang or Emscripten, add attributes to define its import source and name:

// Tell the compiler x is imported from the "env" module with the name "x"
extern int x __attribute__((import_module("env"), import_name("x")));

int foo() {
    return x;
}

Compile this to WASM with a command like (using Clang):

clang --target=wasm32 -nostdlib -Wl,--export-all,--no-entry -o test.wasm test.c

3. Fix the JavaScript Code

Instead of passing a raw 5, create a WebAssembly.Global that matches the type of x (a 32-bit integer, i32). Also note: the import key should match the import_name we set in C (x, not _x—the leading underscore convention doesn't apply here since we explicitly named the import).

// Create a mutable 32-bit global variable with an initial value of 5
const importedX = new WebAssembly.Global({ value: 'i32', mutable: true }, 5);

const importObj = {
    env: {
        memory: new WebAssembly.Memory({ initial: 256, maximum: 256 }),
        x: importedX // Matches the import_name defined in C
    }
};

WebAssembly.instantiateStreaming(fetch('test.wasm'), importObj)
    .then(result => console.log('Output: ' + result.instance.exports.foo()));

4. Why This Works

  • The C attribute instructs the compiler to generate a WASM module that expects an imported global named x from the env module.
  • The WebAssembly.Global instance in JavaScript provides a valid, typed reference the WASM module can read directly, instead of defaulting to 0 when it can't find a valid import.

After these changes, your foo() function should return the expected value of 5.

内容的提问来源于stack exchange,提问作者MatthewScarpino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:42:05