这是我的 C 代码:
// helloworld.c
#include <stdio.h>
#include <emscripten.h>
int* EMSCRIPTEN_KEEPALIVE getIntArray(){
static int numbers[] = {1, 2, 4, 8, 16};
return numbers;
}
这是我的一些 JS:
// helloworld.html
let result = Module.ccall('getIntArray', // name of C function
'Uint8Array', // return type
[null], // argument types
[null]); // arguments
let array = new Uint8Array(result,5);
console.log(result); // prints 1024
console.log(array); // prints Uint8Array(1024) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, … ]
所有这些都可以正常编译和运行。上面的代码对原始值工作正常,但对数组指针失败,我得到的 JS 类型数组全为零。我在文档中看到了其他一些解决方案,但它们似乎也不适合我。
最佳答案
getIntArray
函数将返回一个整数,它是数组在 WebAssembly 模块线性内存中的位置。为了使用它,您需要引用模块的线性内存。
一种选择是在 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);
然后您可以使用返回的结果(将是一个整数)作为线性内存的偏移量:
const result = Module.ccall('getIntArray', // name of C function
'Uint8Array', // return type
[null], // argument types
[null]); // arguments
const data = new Uint8Array(imports.env.memory.buffer, result, 5);
关于javascript - emscripten - 如何从 JavaScript (Chrome/Firefox) 读取 C 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52547378/