如何将字符串传递给使用 emscripten 为 WebAssembly 编译的 C 代码 [英] How to pass a string to C code compiled with emscripten for WebAssembly

查看:26
本文介绍了如何将字符串传递给使用 emscripten 为 WebAssembly 编译的 C 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找 WebAssembly 网站和教程,但我觉得有点迷茫.

I've been looking a the WebAssembly website and tutorials and I feel a bit lost.

我有以下 C 代码:

void EMSCRIPTEN_KEEPALIVE hello(char * value){
    printf("%s\n", value);
}

我编译它(我也不确定这部分是最好的方法):

I compiled it with (I'm also not sure this part is the best way to go) :

emcc demo.c -s WASM=1 -s NO_EXIT_RUNTIME=1 -o demo.js

据我所知,我现在可以在我的 javascript 类中使用 demo.js 粘合代码并以这种方式调用该方法:

From what I understand I can now use the demo.js glue code in my javascript class and call the method that way :

...
<script src="demo.js"></script>
<script>
    function hello(){        
        // Get the value 
        var value = document.getElementById("sample");
        _hello(value.innerHTML);
    }
</script>
...

当我调用该方法时,我在控制台中看到的打印内容是:

What I see being printed in the console when I call the method is :

(null)

我是否缺少将字符串值传递给使用 WebAssembly 编译的 C 代码的内容?

Is there something I'm missing to pass a string value to C code compiled with WebAssembly ?

非常感谢

推荐答案

我实际上找到了我问题的答案.我只需要在Glue"代码中使用 Emscripten 自动构建的函数,当您将 C++ 代码构建到 WASM 时也会生成这些代码.

I actually found an answer to my question. I simply had to use the functions that Emscripten builds automatically within the 'Glue' code that's also generated when you build your C++ code to WASM.

所以基本上,要将字符串传递给使用 Emscripten 编译为 WebAssembly 的 C++ 代码,您只需这样做:

So basically, to pass a String to C++ code compiled to WebAssembly with Emscripten you simply do it like this :

// Create a pointer using the 'Glue' method and the String value
var ptr  = allocate(intArrayFromString(myStrValue), 'i8', ALLOC_NORMAL);

// Call the method passing the pointer
val retPtr = _hello(ptr);

// Retransform back your pointer to string using 'Glue' method
var resValue = Pointer_stringify(retPtr);

// Free the memory allocated by 'allocate' 
_free(ptr);   

关于Emscripten 的页面.

这篇关于如何将字符串传递给使用 emscripten 为 WebAssembly 编译的 C 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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