Method: Fiddle::Pointer.malloc
- Defined in:
- ext/fiddle/pointer.c
.Fiddle::Pointer.malloc(size, freefunc = nil) ⇒ Object .Fiddle::Pointer.malloc(size, freefunc) {|pointer| ... } ⇒ Object
Examples
# Automatically freeing the pointer when the block is exited - recommended
Fiddle::Pointer.malloc(size, Fiddle::RUBY_FREE) do |pointer|
...
end
# Manually freeing but relying on the garbage collector otherwise
pointer = Fiddle::Pointer.malloc(size, Fiddle::RUBY_FREE)
...
pointer.call_free
# Relying on the garbage collector - may lead to unlimited memory allocated before freeing any, but safe
pointer = Fiddle::Pointer.malloc(size, Fiddle::RUBY_FREE)
...
# Only manually freeing
pointer = Fiddle::Pointer.malloc(size)
begin
...
ensure
Fiddle.free pointer
end
# No free function and no call to free - the native memory will leak if the pointer is garbage collected
pointer = Fiddle::Pointer.malloc(size)
...
Allocate size bytes of memory and associate it with an optional freefunc.
If a block is supplied, the pointer will be yielded to the block instead of being returned, and the return value of the block will be returned. A freefunc must be supplied if a block is.
If a freefunc is supplied it will be called once, when the pointer is garbage collected or when the block is left if a block is supplied or when the user calls call_free, whichever happens first. freefunc must be an address pointing to a function or an instance of Fiddle::Function.
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 |
# File 'ext/fiddle/pointer.c', line 288 static VALUE rb_fiddle_ptr_s_malloc(int argc, VALUE argv[], VALUE klass) { VALUE size, sym, obj, wrap = 0; long s; freefunc_t f; switch (rb_scan_args(argc, argv, "11", &size, &sym)) { case 1: s = NUM2LONG(size); f = NULL; break; case 2: s = NUM2LONG(size); f = get_freefunc(sym, &wrap); break; default: rb_bug("rb_fiddle_ptr_s_malloc"); } obj = rb_fiddle_ptr_malloc(klass, s,f); if (wrap) RPTR_DATA(obj)->wrap[1] = wrap; if (rb_block_given_p()) { if (!f) { rb_raise(rb_eArgError, "a free function must be supplied to Fiddle::Pointer.malloc when it is called with a block"); } return rb_ensure(rb_yield, obj, rb_fiddle_ptr_call_free, obj); } else { return obj; } } |