Reputation: 3044
I'm trying to call JS function from C/C++ with an array of strings as an argument.
Here's my example code:
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>
build:
emcc main.c -o main.html
result I get:
["", "", "", ""]
result I want:
["ab", "cd", "ef", "gh"]
How can I properly convert char **argv
to a JS array of strings?
Upvotes: 2
Views: 938
Reputation: 14607
How can I properly convert
char **argv
to a JS array of strings?
From the documentation of 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 insideEM_JS
code, where they appear as integers likechar *
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;
}
So, you can use HEAP32
along with UTF8ToString
like this:
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;
}
Compile:
emcc main.c -o main.html
Run with node
:
node main.js
Output:
[ 'ab', 'cd', 'ef', 'gh' ]
Upvotes: 4