ruby / fiddle

A libffi wrapper for Ruby.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: How to allocate an array of structs?

kojix2 opened this issue · comments

Hi!

How to allocate an array of structs?
I tried the following code, but it does not work as expected. It may be because the same area is released twice.

require 'fiddle/import'

A = Fiddle::Importer.struct [
  'int x',
  'int y'
]

as = Fiddle::Pointer.malloc(A.size * 3)

structs = Array.new(3){ |i|
  size = A.size
  A.new(as.to_i + i * size, size)
}

Thank you.

A.new's second argument is free function not size: A.new(as.to_i + i * size)

BTW, you must free as.

It's true. I was wrong.

require 'fiddle/import'

A = Fiddle::Importer.struct [
  'int x',
  'int y'
]

as = Fiddle::Pointer.malloc(A.size * 3)

structs = Array.new(3){ |i|
  size = A.size
  A.new(as.to_i + i * size)
}

When a Fiddle::Pointer is collected in garbage collection, is the memory of the pointer not automatically released?
That is, if no function is specified to release it, it will remain until (or even after?) Ruby exits?

You can use the second argument for Fiddle::Pointer.malloc for free function: Fiddle::Pointer.malloc(A.size * 3, Fiddle::RUBY_FREE).

You can also use block:

Fiddle::Pointer.malloc(A.size * 3, Fiddle::RUBY_FREE) do |as|
  # ...
end

Wow. This is very useful.
Good to hear.