Last active
August 1, 2018 10:12
-
-
Save Teaonly/e9271740a9976985a585 to your computer and use it in GitHub Desktop.
如何利用emscripten将C代码转换为javascript代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 如何使用emscripten | |
## 1.下载emsdk,并且利用emsdk下载对应的二进制工具 | |
https://developer.mozilla.org/en-US/docs/Emscripten/Download_and_install | |
## 配置emsdk | |
在下载esmsdk_portable目录下,执行: | |
``` | |
emsdk activate | |
``` | |
然后在需要使用emsdk的时候,执行以下命令,将必要的命令加入PATH环境 | |
``` | |
sourc ./emsdk_add_path | |
``` | |
这样的话就可以直接执行emcc编译器了。 | |
# 如何在Javascript 和 C语言函数之间交换数据 | |
## 将JS空间内的数据复制到C语言(即HEAP)空间的数据 | |
``` | |
var inputBuf = new Uint8Array(1024); | |
var inputMemory = Module._malloc(inputBuf.length*inputBuf.BYTES_PER_ELEMENT); | |
inputBuf[0] = 0x12; | |
inputBuf[1] = 0x34; | |
inputBuf[2] = 0x56; | |
Module.HEAPU8.set(inputBuf, inputMemory); //完成数据复制,长度以inputBuf作为数据长度 | |
``` | |
## 调用C语言函数,使用malloc空间,即使用memory, 不使用buffer | |
``` | |
var outputMemory = Module._malloc(1024); | |
var samples = Module._doDecode(inputMemory, 3, outputMemory); | |
``` | |
## 从C空间的memory复制到Javascript空间的Buffer | |
``` | |
var outputBuffer = Module.HEAPU8.subarray(outputMemory, outputMemory + 1024); | |
``` | |
## 所有malloc分配的空间,最后需要释放 | |
``` | |
Module._malloc(intputMemory); | |
Module._malloc(outputMemory); | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment