3

I'm trying to pass a char* array to the Emscripten compiled function, and haven't figured out how to do it properly.

All the examples(here, and here) I found so far are about passing number array which however cannot be applied to char* array directly. The Emscripten docs mentions that a typed array has to be Unit8Array or Int8Array.

the third is an array of parameter types...“array” (for a JavaScript array or typed array that corresponds to a C array; for typed arrays, it must be a Uint8Array or Int8Array)...

Does it mean we need to convert the string array into either of these formats and revert it back on C++ side? And, what's the difference between a JS array and a typed array? I don't think a number array needs this explicit conversion.

JS code:

var myFunc = Module.cwrap('myFunc', 'number', ['string', 'array', 'number']);
var strArr = ['abc', 'def', 'ghi', 'jkl'];
var rst = myFunc('abc', strArr, 0);

C++ code:

int myFunc(char* str, char** strArr, int i) {
  std::cout << "[C++] The i is " << i << std::endl; // 0
  std::cout << "[C++] The str is " << str << std::endl; // abc
  std::cout << "[C++] The strArr[i] is " << strArr[i] << std::endl; // not 'abc' ??
  return strcmp(str, strArr[i]);
}

1 Answer 1

2

We can convert strArr to char** JavaScript side. But if you modify c++ code, Embind would be better.

var myFunc = Module.cwrap('myFunc', 'number', ['string', 'number', 'number']);

Runtime.stackSave();
var strArr = ['abc', 'def', 'ghi', 'jkl'];
var ptrArr = Runtime.stackAlloc(strArr.length * 4);
for (var i = 0; i < strArr.length; i++) {
    var len = strArr[i].length + 1;
    var ptr = Runtime.stackAlloc(len);
    stringToUTF8(strArr[i], ptr, len);
    Module.setValue(ptrArr + i * 4, ptr, "i32");
}
var rst = myFunc('abc', ptrArr, 1);
Runtime.stackRestore();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.