使用CMake时如何在Emscripten中导出C函数 [英] How to export C function in Emscripten when using CMake

查看:86
本文介绍了使用CMake时如何在Emscripten中导出C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In this tutorial it shows the following example for exporting C functions

./emcc tests/hello_function.cpp -o function.html -s EXPORTED_FUNCTIONS='["_int_sqrt"]' -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]'

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

I would like to do the same except that I use CMake like this

cd bin
emcmake cmake ../src
emmake make

在emmake中指定 -s 的规范方法是什么?我是否应该将其添加到 CMakeLists.txt 之类的

What is the canonical way of specifying -s in emmake? Should I add it to CMakeLists.txt like

set(EXPORTED_FUNCTIONS '["_int_sqrt"]')

还是做类似的事情?

推荐答案

到目前为止,我发现可以通过以下设置实现CMake

What I figured out so far is that it can be achieved CMake with the following settings

# 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函数,如下所示:

Then you should be able to call C functions from javascript as follows:

<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函数的定义:

And this is my definition of C function:

#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int testInt(){
    return 69420;
}

这篇关于使用CMake时如何在Emscripten中导出C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆