我将一组数据传递给 WebAssembly 函数:
const input = Module._malloc(size);
[fill up buffer...]
Module.HEAP8.set(size, input);
Module.someCall(input);
Run Code Online (Sandbox Code Playgroud)
这有效。事实上,_malloc 是模块的一部分。但是,免费功能不是。尝试使用DEFAULT_LIBRARY_FUNCS_TO_INCLUDE和EXTRA_EXPORTED_RUNTIME_METHODS。也尝试实现我自己的免费功能:
EMSCRIPTEN_KEEPALIVE
void free(void *ptr) {
free(ptr);
}
Run Code Online (Sandbox Code Playgroud)
编译:
emcc -O3 -s WASM=1 test.c -o test.js
Run Code Online (Sandbox Code Playgroud)
但没有运气。要么_free在模块中找不到。要么,通过在我的 C 代码中定义上述函数,该函数存在于 Module 中,但它什么也不做,我最终会耗尽内存。Doc 在这个主题上很少。
有人知道如何检索实际释放我的缓冲区的自由函数吗?
可能是你没有正确编译代码。
这是我的样本。
创建一个test.c文件:
#include <stdlib.h>
#include <stdint.h>
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
EMSCRIPTEN_KEEPALIVE
uint8_t* create(int width, int height) {
return malloc(width * height * 4 * sizeof(uint8_t));
}
EMSCRIPTEN_KEEPALIVE
void destroy(uint8_t* p) {
free(p);
}
Run Code Online (Sandbox Code Playgroud)
编译代码:
emcc test.c -O2 -s WASM=1 -Wall -s MODULARIZE=1 -o test.js
Run Code Online (Sandbox Code Playgroud)
创建一个index.js文件:
const Module = require('./test.js');
const wasm = Module({wasmBinaryFile: 'test.wasm'});
wasm.onRuntimeInitialized = function() {
console.log(wasm._add(40, 40));
let mem = wasm._create(100, 100);
wasm._destroy(mem);
console.log("Done");
};
Run Code Online (Sandbox Code Playgroud)
在 Node.js 中运行它:
node index.js
Run Code Online (Sandbox Code Playgroud)
在网页上运行它:
<script type="text/javascript">
var wa_add, wa_create, was_destroy, wasm;
function add() {
let int1 = document.getElementById('int1').value;
let int2 = document.getElementById('int2').value;
if (wa_add) {
document.getElementById('result').innerText = wa_add(parseInt(int1), parseInt(int2));
// API test
if (wa_create && was_destroy) {
let canvas = document.getElementById('image');
var ctx = canvas.getContext('2d');
var image = ctx.getImageData(0, 0, canvas.width, canvas.height);
const p = wa_create(canvas.width, canvas.height);
wasm.HEAP8.set(image.data, p);
// Do something for the image buffer.
was_destroy(p);
}
} else {
document.getElementById('result').innerText = parseInt(int1) + parseInt(int2);
}
}
if (Module) {
wasm = Module({
wasmBinaryFile: 'test.wasm'
});
wasm.onRuntimeInitialized = function () {
document.getElementById('anim-loading').style.display = 'none';
wa_add = wasm._add;
wa_create = wasm._create;
was_destroy = wasm._destroy;
};
}
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1918 次 |
| 最近记录: |