gpt4 book ai didi

javascript - 包含标准库时出现 WebAssembly LinkError

转载 作者:行者123 更新时间:2023-11-30 16:20:48 24 4
gpt4 key购买 nike

这个非常简单的 WebAssembly 程序对我来说效果很好:

测试.c

int testing(void) {
return 10;
}
int main(void) {
return 0;
}

test.html

<html>
<body>
<script>
var imports = {};

function instantiate(bytes, imports) {
return WebAssembly.compile(bytes).then(m => new WebAssembly.Instance(m, imports));
}
fetch('test.wasm').then(response => response.arrayBuffer())
.then(bytes => instantiate(bytes, imports))
.then(instance => {
console.log(instance.exports._testing());
} );

</script>
</body>
</html>

我正在使用:

emcc test.c something.c -s "EXPORTED_FUNCTIONS=['_testing']" -s WASM=1 -O3 -o test.wasm

但是,如果我尝试这样的事情:

测试.c

#include <stdio.h>
int testing(void) {
printf("Hello!\n");
return 10;
}
int main(void) {
return 0;
}

首先,它会产生以下错误:

TypeError: import object field 'env' is not an Object

我尝试通过向 imports 添加 env 字段来解决这个问题:

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

但这只会给我带来另一个错误:

LinkError: import object field '___syscall146' is not a Function

我也尝试过使用 -s EXPORT_ALL=1,但这只是稍微改变了错误消息:

LinkError: import object field '___setErrNo' is not a Function

我对 WebAssembly 不太了解,所以我不确定这里发生了什么。到底是什么导致了这个错误?

编辑:

有趣的是,如果我调用 malloc,我根本不会收到任何错误:

#include <stdlib.h>
int testing(void) {
int* p = malloc(5);
*p = 17;
free(p);
return 7;
}
int main(void) {
return 0;
}

但是如果我从任何分配的内存中返回值:

#include <stdlib.h>
int testing(void) {
int* p = malloc(5);
*p = 17;
free(p);
return *p;
}
int main(void) {
return 0;
}

我再次得到这个:

LinkError: import object field '___setErrNo' is not a Function

从错误消息来看,emcc 似乎没有链接标准库(也许?),但我找不到其他有同样问题的人...

最佳答案

我终于通过让 emcc 直接输出 .js 文件来让它工作:

测试.c

#include <stdio.h>

void testing(void) {
printf("Hello!\n");
}

int main(void) {
return 0;
}

test.html

<html>
<body>
<script src="test.js"></script>
<script>
Module.onRuntimeInitialized = function() {
_testing();
}
</script>

</body>
</html>
emcc test.c -s EXPORTED_FUNCTIONS=['_testing'] -s WASM=1 -O3 -o test.js

我仍然不完全确定之前出了什么问题......但至少现在可以了。

关于javascript - 包含标准库时出现 WebAssembly LinkError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170692/

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