Subject: Re: [ruby-ffi] Struct/ManagedStruct and GC behaviour |
From: Wayne Meissner |
Date: 12/21/09 4:20 PM |
To: ruby-ffi@googlegroups.com |
2009/12/22 Thomas E Enebo <tom.enebo@gmail.com>:
I have been wondering about the Struct API myself. It seems like it should support a simple explicit memory management API ala: class MyFFIStruct < FFI::Struct .... MyFFIStruct.new do|struct_instance|
some_ffi_call struct_instance # Do other stuff.... end # I know the block has disposed of my allocated struct
It does support this indirectly via MemoryPointer.new
e.g.
MemoryPointer.new(MyFFIStruct.size) do |p|
s = MyFFIStruct.new(p)
some_ffi_call s
# do other stuff
end
An alternative is to use FFI::Buffer as the backing memory - on JRuby,
that is jvm-heap memory, which is copied in/out of a temporary native
memory area (usually on the stack) when passed to a native function.
For small structs, especially ones that are passed to a native
function just once, this can be up to 10x faster than the alloc/free
cycle of a MemoryPointer backed Struct.