下面看具體的實例。前端
下面的代碼是一個C函數,實現簡單的字符串拼接,而後返回拼接的字符串。編程
#include <stdio.h> #include <string> char* EMSCRIPTEN_KEEPALIVE outName(char *n){ char xhName[] = "xuanhun"; strcat(n, xhName); return n; }
下面使用命令進行編譯:數組
emcc hello.cc -o test2.js
而後在頁面中引用:函數
<script> Module = {}; Module.onRuntimeInitialized = function () { var ptr = allocate(intArrayFromString("玄魂"), 'i8', ALLOC_NORMAL); var retPtr = Module._outName(ptr); var resValue = Pointer_stringify(retPtr); console.log(resValue); _free(ptr); } </script> <script src="test2.js"></script>
上面的代碼咱們核心部分逐行分析一下:3d
var ptr = allocate(intArrayFromString("玄魂"), 'i8', ALLOC_NORMAL);
上面的intArrayFromString方法,將字符串轉換爲UTF8的char數組,而後allocate 方法開闢內存空間存儲數據,返回指針。指針
var retPtr = Module._outName(ptr);
調用C導出函數,傳入字符串指針。code
var resValue = Pointer_stringify(retPtr);
調用Pointer_stringify膠水函數,將c返回的指針轉換爲字符串。blog
_free(ptr);
釋放內存。ip
下面查看下運行結果:內存
WebAssembly編程實踐(1.2)Hello World!
WebAssembly編程實踐(1.1)安裝Emscripten
歡迎關注玄說前端公衆號
QQ羣:850038125