2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RubyのFiddleで確保した構造体のメモリを解放する方法

Last updated at Posted at 2023-03-20

Fiddleとは、Rubyに標準添付されている、ffiのライブラリである。最も普及しているRuby-FFIとは別だが、標準でインストールされている確率が非常に高いので、かんたんにC言語のライブラリを呼びたいときは役に立つ。

Fiddleで構造体のメモリを確保した場合に、どう解放するかについての情報がネット上にそれほどないのでまとめる。

require "fiddle/import"

module FFI
  extend Fiddle::Importer
  A = struct(["int a", "int b"])
end

a = FFI::A.malloc

として構造体Aを定義して、Aのメモリを確保した場合、ローカル変数 a がRubyのGCによって回収されても、Rubyが終了するまで、確保されたメモリは残っている。

一方で、最近のFiddleでは

a = FFI::A.malloc(Fiddle::RUBY_FREE)

古いFiddleでは

a.to_ptr.free = Fiddle::RUBY_FREE

とすることで、GCで a が回収されるタイミングで、確保されたメモリが解放される。

したがって、一定時間ののちに終了することがわかっているRubyスクリプトは、メモリを確保しっぱなしでも実害はないと思うが、長時間実行するRubyのコードの場合には、適切なタイミングでメモリが解放されるように気をつけたい。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?