简体   繁体   中英

How to pass char* array to emscripten compiled code?

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]);
}

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM