WebAssembly01-- 在js中分配内存

简介: WebAssembly01-- 在js中分配内存

编译选项

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>

目录
相关文章
|
2月前
|
存储 缓存 JavaScript
请描述一种JavaScript内存泄漏的情况,并说明如何避免这种情况的发生。
JavaScript内存泄漏常由闭包引起,导致无用对象滞留内存,影响性能。例如,当一个函数返回访问大型对象的闭包,即使函数执行完,对象仍被闭包引用,无法被垃圾回收。防止泄漏需及时解除引用,注意事件监听器清理,使用WeakMap或WeakSet,定期清理缓存,以及利用性能分析工具检测。
13 2
|
2月前
|
存储 程序员 编译器
在C语言中.如何正确地分配和释放内存docx
在C语言中.如何正确地分配和释放内存docx
17 1
|
2月前
|
存储 C++
C/C++数据类型从0到内存具体分配详解
C/C++数据类型从0到内存具体分配详解
|
2月前
关于为什么要在链表中用malloc来分配内存
关于为什么要在链表中用malloc来分配内存
|
9天前
为对象分配内存TLAB
为对象分配内存TLAB
|
9天前
|
存储 缓存 JavaScript
【Web 前端】JS哪些操作会造成内存泄露?
【4月更文挑战第22天】【Web 前端】JS哪些操作会造成内存泄露?
|
22天前
|
JavaScript 前端开发
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory 内存溢出问题
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory 内存溢出问题
17 1
|
1月前
|
JavaScript 前端开发 Java
JavaScript中的内存泄露:如何避免及修复
JavaScript中的内存泄露:如何避免及修复
30 3
|
2月前
|
存储 编译器 程序员
【C语言】内存的动态分配与释放
【C语言】内存的动态分配与释放
28 0
|
2月前
|
存储 C语言
怎样建立内存的动态分配
怎样建立内存的动态分配
8 0