Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
class method
Fiddle::Pointer.malloc
malloc(size, free = nil) { |pointer| ... }
ext/fiddle/lib/fiddle/ffi_backend.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.4.1/ext/fiddle/lib/fiddle/ffi_backend.rb, line 338
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
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.