Advertisement
Guest User

simple array of Objects that are adjacent in memory in D

a guest
Apr 26th, 2011
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 0.82 KB | None | 0 0
  1. // note that you probably shouldn't slice the resulting array or assign new objects to it
  2. T[] myNewArr(T, Args...) (size_t len, Args args) {
  3.     // get class size of class object in bytes
  4.     size_t clSize = __traits(classInstanceSize, T);
  5.     // allocate memory for the objects - maybe even with GC malloc
  6.     void* tmp = malloc( clSize * len );
  7.     if(!tmp) throw new Exception("no memory");
  8.     T[] ret; // remember - this just contains references
  9.  
  10.     for(size_t i=0;i<len;++i) {
  11.         size_t pos = i*clSize;
  12.         void[] objMem = tmp[pos..pos+clSize];
  13.         // add reference to new object to array
  14.         ret ~= emplace!(T, Args)(objMem, args);
  15.     }
  16.  
  17.     return ret;
  18. }
  19.  
  20. void myDeleteArr(T)(ref T[] arr) {
  21.     void *adr = cast(void*)arr[0];
  22.     foreach(elem; arr)
  23.         clear(elem);
  24.     // core.stdc.stdlib.free(adr);
  25.     arr=null; // so the data will be freed
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement