Method: Fiddle::Pointer.malloc

Defined in:
ext/fiddle/pointer.c,
lib/fiddle/ffi_backend.rb

.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.

Overloads:

  • .Fiddle::Pointer.malloc(size, freefunc) {|pointer| ... } ⇒ Object

    Yields:

    • (pointer)


301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'ext/fiddle/pointer.c', line 301

def self.malloc(size, free = nil)
  if block_given? and free.nil?
    message = "a free function must be supplied to #{self}.malloc " +
              "when it is called with a block"
    raise ArgumentError, message
  end

  pointer = new(LibC.malloc(size), size, free)
  if block_given?
    begin
      yield(pointer)
    ensure
      pointer.call_free
    end
  else
    pointer
  end
end