gpt4 book ai didi

javascript - EM_JS:如何将int argc,char ** argv转换为字符串的JS数组?

转载 作者:行者123 更新时间:2023-12-02 10:11:39 24 4
gpt4 key购买 nike

我试图用字符串数组作为参数从C / C++调用JS函数。
这是我的示例代码:
main.c:

#include <stdio.h>
#include <emscripten.h>

EM_JS(void, call_myFunc, (int argc, char **argv), {

var arr = [];
for (let i = 0; i < argc; i++) {
arr.push(UTF8ToString(argv[i]));
}
myFunc(arr);
});

int main()
{
int argc = 4;
char *argv[5] = { "ab", "cd", "ef", "gh" };
call_myFunc(argc, argv);
}
index.html:
<!DOCTYPE html>
<html>

<head>
</head>

<body>
<script>
function myFunc(args) {
console.log(args);
}
</script>
<script async src="main.js"></script>
</body>

</html>
版本:
emcc main.c -o main.html
我得到的 结果:
["", "", "", ""]
我想要的 结果:
["ab", "cd", "ef", "gh"]
如何将 char **argv正确转换为JS字符串数组?

最佳答案

How can I properly convert char **argv to a JS array of strings?


emscripten.h 的文档中:

Null-terminated C strings can also be passed into EM_JS functions, but to operate on them, they need to be copied out from the heap to convert to high-level JavaScript strings.

EM_JS(void, say_hello, (const char* str), {
console.log('hello ' + UTF8ToString(str));
}

In the same manner, pointers to any type (including void *) can be passed inside EM_JS code, where they appear as integers like char * pointers above did. Accessing the data can be managed by reading the heap directly.

EM_JS(void, read_data, (int* data), {
console.log('Data: ' + HEAP32[data>>2] + ', ' + HEAP32[(data+4)>>2]);
});

int main() {
int arr[2] = { 30, 45 };
read_data(arr);
return 0;
}

因此,您可以像这样将 HEAP32UTF8ToString一起使用:
main.c
#include <stdio.h>
#include <emscripten.h>

EM_JS(void, call_myFunc, (const int argc, const char** argv), {
var arr = [];
for (let i = 0; i < argc; i++) {
const mem = HEAP32[(argv + (i * 4)) >> 2];
const str = UTF8ToString(mem);
arr.push(str);
}
console.log(arr);
});

int main() {
const int argc = 4;
const char* argv[] = { "ab", "cd", "ef", "gh" };
call_myFunc(argc, argv);
return 0;
}
编译:
emcc main.c -o main.html
使用 node运行:
node main.js
输出:
[ 'ab', 'cd', 'ef', 'gh' ]

关于javascript - EM_JS:如何将int argc,char ** argv转换为字符串的JS数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63321398/

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