js怎么调用wasm_javascript-如何协调主机JS和WASM模块之间的内存访问?

当前,Webassembly仅支持a handful of parameter types,即固定大小的整数和浮点数.这意味着我只能从接受和返回数值的C / Rust模块中定义和导出函数.

[M]emory created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly.

这听起来非常有前途-这表明我可以将内存的一部分指定为字节缓冲区,以便在其中跨语言障碍来回传递更复杂的数据.我模块中的函数可以接受和返回指针(它们本身是i32,固定大小的整数),从而在当前约束下工作.

不幸的是,目前尚不清楚我应该如何管理该内存.如果需要将数据从JS传递到WASM进程,则需要直接写入Memory对象,但不知道Memory中的哪些区域可用.

最安全的策略是什么?是否应该导出一对malloc-and-free-style函数,这些函数为JS提供了在调用WASM之前请求内存的方法?还是有既定的最佳实践?

解决方法:

我认为最简单的方法是使用Emscripten,并使用其内置的malloc / free.然后导出一个函数,该函数在C中分配通过该malloc / free请求的内存,并返回指针.这样,JavaScript可以调用WebAssembly以获取尚未使用的可用内存区域.

我已经详细说明了如何在this answer中与JS / wasm共享字符串/从JS / wasm共享字符串,上面有一些细节.

请注意,WebAssembly中的指针并不是真正的东西. C只是将它们映射到从0开始的Memory.因此,当对ArrayBuffer进行索引时,只需要C的指针,就不需要额外的映射.

标签:webassembly,memory,memory-management,javascript

来源: https://codeday.me/bug/20191111/2019259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是我 运行终端代码后的返回,请帮我解释下:shenhaibo@bogon webAssembly % emcc add.c -s WASM=1 -o add.wasm wasm-ld: error: /opt/homebrew/Cellar/emscripten/3.1.40/libexec/cache/sysroot/lib/wasm32-emscripten/libstandalonewasm-nocatch.a(__main_void.o): undefined symbol: main emcc: error: '/opt/homebrew/Cellar/emscripten/3.1.40/libexec/llvm/bin/wasm-ld -o add.wasm /var/folders/hd/zkctfvz128366gcjfw9pgslr0000gn/T/emscripten_temp_0gmz58hs/add_0.o -L/opt/homebrew/Cellar/emscripten/3.1.40/libexec/cache/sysroot/lib/wasm32-emscripten /opt/homebrew/Cellar/emscripten/3.1.40/libexec/cache/sysroot/lib/wasm32-emscripten/crt1.o -lGL -lal -lhtml5 -lstandalonewasm-nocatch -lstubs-debug -lc-debug -ldlmalloc -lcompiler_rt -lc++-noexcept -lc++abi-debug-noexcept -lsockets -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr /var/folders/hd/zkctfvz128366gcjfw9pgslr0000gn/T/tmp6m8wb6r0libemscripten_js_symbols.so --strip-debug --export-if-defined=__start_em_asm --export-if-defined=__stop_em_asm --export-if-defined=__start_em_lib_deps --export-if-defined=__stop_em_lib_deps --export-if-defined=__start_em_js --export-if-defined=__stop_em_js --export=emscripten_stack_get_end --export=emscripten_stack_get_free --export=emscripten_stack_get_base --export=emscripten_stack_get_current --export=emscripten_stack_init --export=stackSave --export=stackRestore --export=stackAlloc --export=__errno_location --export-table -z stack-size=65536 --initial-memory=16777216 --max-memory=16777216 --stack-first' failed (returned 1) shenhaibo@bogon webAssembly %
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值