官方文档是这样说的: cwrap uses the C stack for temporary values. If you pass a string then it is only “alive” until the call is complete. If the code being called saves the pointer to be used later, it may point to invalid data. If you need a string to live forever, you can create it, for example, using _malloc and stringToUTF8(). However, you must later delete it manually!
可以使用Module._malloc()和Module.stringToUTF8()函数通过heap来传递大量数据: [cpp] const bufferSize = Module.lengthBytesUTF8(veryLargeString) + 1; const bufferPtr = Module._malloc(bufferSize); Module.stringToUTF8(veryLargeString, bufferPtr, bufferSize); const sample = Module.cwrap(‘sample’, null, [‘number’]); // not ‘string’, pointer is a number sample(bufferPtr); Module._free(bufferPtr); [/cpp]
还有一个更简洁的包装方法allocateUTF8可用,直接传递给它数据,它就可以将数据拷贝到堆上,并返回在heap上分配的空间地址,这样用: [cpp] const bufferPtr = allocateUTF8(veryLargeString); const sample = Module.cwrap(‘sample’, null, [‘number’]); // not ‘string’, pointer is a number sample(bufferPtr); Module._free(bufferPtr); [/cpp]
allocateUTF8的源代码: [javascript] // Allocate heap space for a JS string, and write it there. // It is the responsibility of the caller to free() that memory. function allocateUTF8(str) { var size = lengthBytesUTF8(str) + 1; var ret = _malloc(size); if (ret) stringToUTF8Array(str, HEAP8, ret, size); return ret; } [/javascript]
[javascript] // Given a pointer ‘ptr’ to a null-terminated UTF8-encoded string in the emscripten HEAP, returns // a copy of that string as a Javascript String object.
function UTF8ToString(ptr) { return UTF8ArrayToString(HEAPU8,ptr); } [/javascript]