Skip to content

Commit 1ac3d4e

Browse files
committed
Switched to AutoPointer for Booster [skip ci]
1 parent 0de57e5 commit 1ac3d4e

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

lib/lightgbm/booster.rb

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,22 @@ class Booster
33
attr_accessor :best_iteration, :train_data_name
44

55
def initialize(params: nil, train_set: nil, model_file: nil, model_str: nil)
6-
@handle = ::FFI::MemoryPointer.new(:pointer)
76
if model_str
87
model_from_string(model_str)
98
elsif model_file
109
out_num_iterations = ::FFI::MemoryPointer.new(:int)
11-
check_result FFI.LGBM_BoosterCreateFromModelfile(model_file, out_num_iterations, @handle)
10+
::FFI::MemoryPointer.new(:pointer) do |handle|
11+
check_result FFI.LGBM_BoosterCreateFromModelfile(model_file, out_num_iterations, handle)
12+
@handle = ::FFI::AutoPointer.new(handle.read_pointer, FFI.method(:LGBM_BoosterFree))
13+
end
1214
else
1315
params ||= {}
1416
set_verbosity(params)
15-
check_result FFI.LGBM_BoosterCreate(train_set.handle_pointer, params_str(params), @handle)
17+
::FFI::MemoryPointer.new(:pointer) do |handle|
18+
check_result FFI.LGBM_BoosterCreate(train_set.handle_pointer, params_str(params), handle)
19+
@handle = ::FFI::AutoPointer.new(handle.read_pointer, FFI.method(:LGBM_BoosterFree))
20+
end
1621
end
17-
ObjectSpace.define_finalizer(@handle, self.class.finalize(handle_pointer.to_i))
1822

1923
self.best_iteration = -1
2024

@@ -98,7 +102,10 @@ def feature_name
98102

99103
def model_from_string(model_str)
100104
out_num_iterations = ::FFI::MemoryPointer.new(:int)
101-
check_result FFI.LGBM_BoosterLoadModelFromString(model_str, out_num_iterations, @handle)
105+
::FFI::MemoryPointer.new(:pointer) do |handle|
106+
check_result FFI.LGBM_BoosterLoadModelFromString(model_str, out_num_iterations, handle)
107+
@handle = ::FFI::AutoPointer.new(handle.read_pointer, FFI.method(:LGBM_BoosterFree))
108+
end
102109
@cached_feature_name = nil
103110
self
104111
end
@@ -187,15 +194,10 @@ def update
187194
finished.read_int == 1
188195
end
189196

190-
def self.finalize(addr)
191-
# must use proc instead of stabby lambda
192-
proc { FFI.LGBM_BoosterFree(::FFI::Pointer.new(:pointer, addr)) }
193-
end
194-
195197
private
196198

197199
def handle_pointer
198-
@handle.read_pointer
200+
@handle
199201
end
200202

201203
def eval_counts

0 commit comments

Comments
 (0)