1 module ddsp.util.memory; 2 3 import dplug.core.nogc; 4 5 6 /// Template for allocating single instances of class or arrays of classes 7 /// for multiple channels. 8 template calloc(alias EffectName) 9 { 10 private import core.stdc.stdlib : malloc; 11 12 /// Returns an initialized array of the given template parameter. 13 EffectName[] numChannels(Args...)(int n, Args args) nothrow @nogc 14 { 15 EffectName* e = cast(EffectName*)malloc(EffectName.sizeof * n); 16 foreach(chan; 0..n) 17 e[chan] = mallocNew!EffectName(args); 18 return e[0..n]; 19 } 20 21 /// Returns a new instance of EffectName 22 EffectName init(Args...)(Args args) 23 { 24 return mallocNew!EffectName(args); 25 } 26 } 27 28 unittest 29 { 30 import ddsp.effect.compressor; 31 32 Compressor[] compChannel = calloc!Compressor.numChannels(2); 33 Compressor comp = calloc!Compressor.init(); 34 } 35 36 /// Allocates a slice of memory of type T and with the specified length. 37 /// Since dynamic arrays cannot be 38 T[] callocSlice(T)(size_t length) nothrow @nogc 39 { 40 T* mem = cast(T*)malloc(T.sizeof * length); 41 return mem[0..length]; 42 } 43 44 /// Free memory from slice created with callocSlice 45 void freeSlice(T)(T[] slice) 46 { 47 free(cast(T*)slice); 48 } 49 50 unittest 51 { 52 import std.stdio; 53 char[] s = callocSlice!char(200); 54 s.freeSlice(); 55 }