使用 CMake 时如何导出 Emscripten 中的 C 函数

ala*_*ris 5 c cmake emscripten emmake

本教程中,它展示了以下导出 C 函数的示例

./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS='["_int_sqrt"]' -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'
Run Code Online (Sandbox Code Playgroud)

我想做同样的事情,除了我像这样使用 CMake

cd bin
emcmake cmake ../src
emmake make
Run Code Online (Sandbox Code Playgroud)

emmake 中指定的规范方式是什么-s?我应该添加它来CMakeLists.txt喜欢吗

set(EXPORTED_FUNCTIONS '["_int_sqrt"]')
Run Code Online (Sandbox Code Playgroud)

或者做类似的事情?

ala*_*ris 3

到目前为止我发现可以通过以下设置来实现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")
Run Code Online (Sandbox Code Playgroud)

然后你应该能够从 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>
Run Code Online (Sandbox Code Playgroud)

这是我对 C 函数的定义:

#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int testInt(){
    return 69420;
}
Run Code Online (Sandbox Code Playgroud)

  • 你好。在现代 CMake 中不鼓励使用“add_definitions”,因为它会影响所有目标,上面建议的“target_compile_flags”更可取。另外,根据 [Emscripten QA](https://emscripten.org/docs/getting_started/FAQ.html#why-do-functions-in-my-cc-source-code-vanish-when-i-compile-to -javascript-and-or-i-get-no-functions-to-process): ```EMSCRIPTEN_KEEPALIVE 也会导出该函数,就像它在 EXPORTED_FUNCTIONS 上一样。``` (3认同)