从前端将客户端文件传递到Webassembly [英] Passing client files to webassembly from the front-end
问题描述
我希望将用户提交的数据传递给我编译为wasm的c ++函数.数据是用户通过输入标签在前端提交的文件,如下所示:
I'm looking to pass user-submitted data to a c++ function which I've compiled to wasm. The data is a file which the user submits on the front end via an input tag, like so:
<input type="file" onChange={this.handleFile.bind(this)} />
onChange回调当前看起来像这样:
The onChange callback currently looks like this:
handleFile(e){
const file = e.currentTarget.files[0];
const reader = new FileReader();
reader.onloadend = evt => {
window.Module.readFile(evt.target.result);
}
reader.readAsArrayBuffer(file);
}
最后,包含readFile函数的.cpp文件如下所示:
Finally, the .cpp file containing the readFile function looks like this:
void readFile(const std::string & rawString){
std::vector<uint8_t> data(rawString.begin(), rawString.end());
//...
}
EMSCRIPTEN_BINDINGS(my_module) {
emscripten::function("readFile", &readFile);
}
我已经花了一个下午的时间阅读各种文档,所以我意识到我应该为堆上的这些文件分配内存,然后将ptr从js传递到readFile而不是传递所有数据.我的问题是,我只是不太了解所有这些工作原理.有人可以解释吗?
I've spend my afternoon reading various docs so I'm aware that I'm supposed to allocate memory for these files on the heap and then pass a ptr from js to readFile instead of passing all of the data. My problem is that I just don't really understand how all of that is supposed to work. Could someone explain?
推荐答案
借助Emscripten,您可以将虚拟文件系统用于WASM.首先,使用 -s FORCE_FILESYSTEM = 1
选项编译C/C ++代码.在C/C ++内部,您只需照常使用标准库函数来处理文件.在HTML页面上,您有一个 input type = file
元素.
With Emscripten you can use a virtual file system for WASM.
First, you compile your C/C++ code with -s FORCE_FILESYSTEM=1
option.
Inside the C/C++, you just work with files as usual, with standard library functions.
At the HTML page you have an input type=file
element.
示例JS代码以从输入元素获取文件并将其传递到WASM:
Sample JS code to get the file from the input element and pass it into the WASM:
function useFileInput(fileInput) {
if (fileInput.files.length == 0)
return;
var file = fileInput.files[0];
var fr = new FileReader();
fr.onload = function () {
var data = new Uint8Array(fr.result);
Module['FS_createDataFile']('/', 'filename', data, true, true, true);
Module.ccall('YourCppFunctionToUtilizeTheFile', null, [], null);
fileInput.value = '';
};
fr.readAsArrayBuffer(file);
}
链接:
这篇关于从前端将客户端文件传递到Webassembly的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!