webassemblyemscripten

WASM - Emscripten - Can't run ccall, cwrap or FS but I can call methods directly


I've compile a c library to WASM via Emscripten. I'm working on Windows, however, the conversion was done on WSL running Ubuntu.

What I'm finding is I can access methods in the library directly as follows:

var result = Module._myMethod();

But if I try and use cwrap for example it fails:

var myMethod = Module.cwrap("_myMethod", "number", []);
var result = myMethod();

I'll get an error like:

Error in someFunction: TypeError: myMethod is not a function

Similarly if I try and use Emscripten File Storage as follows:

Module.FS_createDataFile('/', 'myFile', 'File content', true, true);

I'll get an error:

Error in changeText: TypeError: Module.FS_createDataFile is not a function

I use the following commands to generate the WASM files:

cmake .. -DCMAKE_TOOLCHAIN_FILE=/mnt/c/.../Platform/Emscripten.cmake
make

My CMakeList.txt file contains the following:

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} \
  -s WASM=1 \
  -s ENVIRONMENT=web \
  -s ALLOW_MEMORY_GROWTH=1 \
  -s ERROR_ON_UNDEFINED_SYMBOLS=0 \
  -s EXPORTED_FUNCTIONS=\"['_main', '_myMethod']\" \
  -s EXPORTED_RUNTIME_METHODS=\"['ccall', 'cwrap', 'FS']\" \
  -DNDEBUG -Oz")

Why is it I can run methods directly, but not via ccall, cwrap or FS?


Solution

  • Figured it out.

    In order to use cwrap you need to remove the underscore on the function name:

    var myMethod = Module.cwrap("myMethod", "number", []);
    var result = myMethod();
    

    For file storage, Module.FS_createDataFile is no longer used, and the current syntax is:

    FS.createDataFile('/', 'myFile', 'File Content', true, true);