|
| 1 | +module c |
| 2 | + |
| 3 | +// When the Boehm collector is used, it is better to replace SDL's memory allocation functions, with versions |
| 4 | +// that Boehm will later know how to process. The callbacks here provide such versions: |
| 5 | +fn cb_malloc_func(size usize) voidptr { |
| 6 | + res := unsafe { malloc(int(size)) } |
| 7 | + $if trace_sdl_memory ? { |
| 8 | + C.fprintf(C.stderr, c'>> sdl.c.cb_malloc_func | size: %lu | => %p\n', size, res) |
| 9 | + } |
| 10 | + return res |
| 11 | +} |
| 12 | + |
| 13 | +fn cb_calloc_func(nmemb usize, size usize) voidptr { |
| 14 | + res := unsafe { vcalloc(isize(nmemb) * isize(size)) } |
| 15 | + $if trace_sdl_memory ? { |
| 16 | + C.fprintf(C.stderr, c'>> sdl.c.cb_calloc_func | nmemb: %lu | size: %lu | => %p\n', |
| 17 | + nmemb, size, res) |
| 18 | + } |
| 19 | + return res |
| 20 | +} |
| 21 | + |
| 22 | +fn cb_realloc_func(mem voidptr, size usize) voidptr { |
| 23 | + res := unsafe { v_realloc(&u8(mem), isize(size)) } |
| 24 | + $if trace_sdl_memory ? { |
| 25 | + C.fprintf(C.stderr, c'>> sdl.c.cb_realloc_func | mem: %p | size: %lu | => %p\n', |
| 26 | + mem, size, res) |
| 27 | + } |
| 28 | + return res |
| 29 | +} |
| 30 | + |
| 31 | +fn cb_free_func(mem voidptr) { |
| 32 | + $if trace_sdl_memory ? { |
| 33 | + C.fprintf(C.stderr, c'>> sdl.c.cb_free_func | mem: %p\n') |
| 34 | + } |
| 35 | + unsafe { free(mem) } |
| 36 | +} |
| 37 | + |
| 38 | +pub type MallocFunc = fn (size usize) voidptr // fn(size usize) voidptr |
| 39 | + |
| 40 | +pub type CallocFunc = fn (nmemb usize, size usize) voidptr // fn(nmemb usize, size usize) voidptr |
| 41 | + |
| 42 | +pub type ReallocFunc = fn (mem voidptr, size usize) voidptr // fn(mem voidptr, size usize) voidptr |
| 43 | + |
| 44 | +pub type FreeFunc = fn (mem voidptr) // fn(mem voidptr) |
| 45 | + |
| 46 | +fn C.SDL_SetMemoryFunctions(malloc_func MallocFunc, calloc_func CallocFunc, realloc_func ReallocFunc, free_func FreeFunc) int |
| 47 | +fn C.SDL_GetNumAllocations() int |
| 48 | + |
| 49 | +fn init() { |
| 50 | + prev_allocations := C.SDL_GetNumAllocations() |
| 51 | + if prev_allocations > 0 { |
| 52 | + eprintln('SDL memory allocation functions should have been replaced with the V ones, but vsdl found, that you did already ${prev_allocations} allocations.') |
| 53 | + return |
| 54 | + } |
| 55 | + replaced := C.SDL_SetMemoryFunctions(cb_malloc_func, cb_calloc_func, cb_realloc_func, |
| 56 | + cb_free_func) |
| 57 | + if replaced != 0 { |
| 58 | + eprintln('SDL memory allocation functions were not replaced.') |
| 59 | + } |
| 60 | +} |
0 commit comments