编译选项
emcc sum.cc -o sum.js -sEXPORTED_FUNCTIONS=_malloc,_free
sum.cc
#include "util.h"
#include<stdlib.h>
#include<string.h>
#include <malloc.h>
EM_PORT_API(int)sum(int*ptr,int count)
{
int total = 0;
for (int i = 0; i < count; i++)
{
total += ptr[i];
}
return total;
}
js_alloc_mem.html
<html>
<head>
<title>test page</title>
</head>
<body>
<script >
Module={}
Module.onRuntimeInitialized=function(){
var count = 50;
var ptr = Module._malloc(count*4);
console.log("sum 50");
for(var i=0;i<count;i++){
Module.HEAP32[ptr/4+i]=i+1;
}
console.log(Module._sum(ptr,count));
Module._free(ptr);
}
</script>
<script src="sum.js"></script>
</body>
</html>
标签:count,total,--,sum,js,int,分配内存,WebAssembly01,include
From: https://www.cnblogs.com/simp/p/16787946.html