提供两种内存分配方式:①简单指针,②句柄(二级指针);官方文档建议使用前者。
// 简单指针
char *ptr;
ptr = sysmem_newptr(2000);
post("I have a pointer %lx and it is %ld bytes in size",ptr, sysmem_ptrsize(ptr));
ptr = sysmem_resizeptrclear(ptr, 3000);
post("Now I have a pointer %lx and it is %ld bytes in size",ptr, sysmem_ptrsize(ptr));
sysmem_freeptr(ptr);
// 句柄
char **hand;
hand = sysmem_newhandle(2000);
post("I have a handle %lx and it is %ld bytes in size",hand, sysmem_handlesize(hand));
sysmem_resizehandle(hand, 3000);
post("Now the handle %lx is %ld bytes in size",hand, sysmem_ptrsize(hand));
sysmem_freehandle(hand);
简单使用示例:
typedef struct _memAlloc {
t_object ob;
char* ptr; // 定义指针
} t_memAlloc;
/* ..... */
void memAlloc_free(t_memAlloc* x) {
sysmem_freeptr(x->ptr); // 释放内存
}
void* memAlloc_new(t_symbol* s, long argc, t_atom* argv) {
t_memAlloc* x = (t_memAlloc*)object_alloc(memAlloc_class);
x->ptr = sysmem_newptr(1024); // 分配内存
post("%lx: %ld bytes", x->ptr, sysmem_ptrsize(x->ptr)); // 打印内存地址和内存大小
return (x);
}
运行结果: