Ruby FFI のメモリ管理についてメモ

Ruby FFI のメモリ管理についてメモ

2010/12/11 12:00am

Ruby FFI のメモリ管理についてメモ。FFI::MemoryPointer で確保したメモリを自分で破棄する場合は、autorelease を false にする。

error   = FFI::MemoryPointer.new(:pointer)
...
C.LLVMDisposeMessage(error)
error.autorelease=false

そうしないと、FFI::MemoryPointer は GC 時に確保したメモリを破棄しようとする (MemoryPointer.c#L138) ので、たとえば Mac OS X では以下のようなエラーが出る。

ruby(891,0x7fff70874ca0) malloc: *** error for object 0x102e8fb10: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

エラー処理とかでは割と忘れがちかもしれない。