到目前为止,我发现可以通过以下设置实现 CMake
# Here you can add -s flag during compiling object files
add_definitions("-s EXPORTED_RUNTIME_METHODS='[\"ccall\",\"cwrap\"]'")
add_definitions("-s EXTRA_EXPORTED_RUNTIME_METHODS='[\"ccall\",\"cwrap\"]'")
add_definitions("-s EXPORTED_FUNCTIONS='[\"_testInt\"]'")
# Here you can add -s flag during linking
set_target_properties(web_mealy_compiler PROPERTIES LINK_FLAGS "-s EXTRA_EXPORTED_RUNTIME_METHODS=['ccall','cwrap']")
# Set this if you want to to generate sample html file
set(CMAKE_EXECUTABLE_SUFFIX ".html")
然后你应该能够从 javascript 调用 C 函数,如下所示:
<script type="text/javascript">
Module['onRuntimeInitialized'] = function() {
console.log("wasm loaded ");
console.log(Module.ccall); // make sure it's not undefined
console.log(Module._testInt); // make sure it's not undefined
console.log(Module._testInt()); // this should work
console.log( Module.ccall('testInt', // name of C function
'number', // return type
[], // argument types
[]) // argument values
);
}
</script>
这是我对 C 函数的定义:
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int testInt(){
return 69420;
}