原文链接:https://github.com/Microsoft/napajs/blob/master/docs/api/memory.md
Namespace memory
Table of Contents
- API
- Type Handle
- Interface Shareable
- Interface Allocator
- allocator.allocate(size: number): Handle
- allocator.deallocate(handle: Handle, sizeHint: number): void
- allocator.type: string
- Interface AllocatorDebugger
- allocatorDebugger.getDebugInfo(): string
- Function debugAllocator(allocator: Allocator):
- AllocatorDebugger
- Object crtAllocator
- Object defaultAllocator
- Memory allocation in C++ addon
API
Handle类型
Handle在TypeScript中按如下方式定义: type Handle = [number, number]
它是Napa中标准的64位指针。
Shareable接口
本地数据封装成可以在多个JavaScript线程间共享的接口。
Allocator接口
内存分配接口,为本地对象分配内存。
allocator.allocate(size: number): Handle
该方法按照请求的大小分配内存。 var handle = allocator.allocate(10);
allocator.deallocate(handle: Handle, sizeHint: number): void
从传入的handle里释放传入大小的内存,这有助于一些C++实例释放内存。 allocator.deallocate(handle, 10);
allocator.type: string
该接口可以获得该分配器字符类型的标识符,在调试期间非常有用。
AllocatorDebugger接口(分配器调试接口)
AllocatorDebugger 继承自Allocator,增加了一个成员函数getDebugInfo 去展示调试信息。
此外,一个分配器的调试器将使用pass-in的分配器进行内存分配。同时,跟踪分配的数量和大小。
allocatorDebugger.getDebugInfo(): string
该函数可以得到调试的分配信息。AllocatorDebugger 接口实例有不同的调试信息模式。
debugAllocator(allocator: Allocator): AllocatorDebugger
该函数返回一个简单的分配器的调试器,返回的调试信息如下:
{
"allocate": 10,
"allocateSize": 1024,
"deallocate": 8,
"deallocateSize": 912
}
Object crtAllocator
它从Napa.js的共享的列表中返回C-runtime 分配器。它的相应的C++部分是 napa::memory::GetCrtAllocator().
对象默认分配器
它从Napa.js的共享的列表中返回默认的分配器。它相应的C++部分是 napa::memory::GetDefaultAllocator().
用户可以在napaallocatorset API里设置默认的分配/解除分配回调函数。
C++插件中的内存分配
C++插件中的内存分配坑比较多。常见的陷阱是在一个dll里分配内存,但是却在另一个里解除分配。如果在这两个dll里的C-runtime未被以同样的方式编译,就会出错。
也有一些用户想要自定义内存分配的高级的场景。Napa.js也提供了供用户自定义内存分配器的APIs。