Passing client files to webassembly from the front-end

前端 未结 2 957
轮回少年
轮回少年 2021-02-14 23:39

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:

2条回答
  •  情歌与酒
    2021-02-15 00:14

    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.

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

    Links:

    1. Emscripten - File System Overview
    2. Here I use the approach, see emulatorAttachFileInput() function

提交回复
热议问题