WebAssembly01--在JavaScript中读写C/C++内存

编译选项

emcc mem.cc -o mem.js

mem.cc

#include "util.h"
int g_int=42;
double g_double = 3.1415926;
EM_PORT_API(int*)get_int_ptr(){
    return &g_int;
}

EM_PORT_API(double*)get_double_ptr()
{
    return &g_double;
}
EM_PORT_API(void)print_data(){
    printf("C{g_int:%d}\n",g_int);
    printf("C{g_double:%lf}\n",g_double);
}

mem.html

<html>
    <head></head>
    <body>
        <script>
            Module={}
            Module.onRuntimeInitialized = function(){
                var int_ptr = Module._get_int_ptr();
                var int_value = Module.HEAP32[int_ptr>>2];
                console.log("JS{int_value:"+int_value+"}");
                var double_ptr = Module._get_double_ptr();
                var double_value = Module.HEAPF64[double_ptr>>3];
                console.log("JS{double_value:"+double_value+"}");

                Module.HEAP32[int_ptr>>2] = 13;
                Module.HEAPF64[double_ptr>>3]=123456.3789;
                Module._print_data();
            }
        </script>
        <script src="mem.js"></script>
    </body>
</html>

运行命令

emrun --no_browser --port 8000 mem.html

运行效果图

简要说明

操作内存是需要字节对齐 这也是上面js代码中右移2 位和3位的原因具体请参照
https://www.cntofu.com/book/150/zh/ch2-c-js/ch2-03-mem-model.md

Module.HEAPX

Emscripten 已经位Module.buffer创建了常用的类型

posted @ 2022-10-12 11:00  simp00  阅读(104)  评论(0编辑  收藏  举报