Skip to content

Instantly share code, notes, and snippets.

@mzumi
Last active November 2, 2016 11:27
Show Gist options
  • Save mzumi/f6fbb960029af0168f6eb94389bde9ab to your computer and use it in GitHub Desktop.
Save mzumi/f6fbb960029af0168f6eb94389bde9ab to your computer and use it in GitHub Desktop.
require 'ffi'
module FFISample
extend FFI::Library
ffi_lib 'target/release/libffi_sample.dylib'
# ガベージコレクタに回収される際に、Rust 側で確保されたメモリ領域を
# 開放するため、ManagedStruct を継承する
class SampleStruct < FFI::ManagedStruct
layout :i, :int,
:b, :bool,
:s, :string
def self.release(ptr)
# Rust 側で割り当てられたヒープ領域を開放する
FFISample.free_sample_struct(ptr)
end
end
attach_function :create_sample_struct, [], :pointer
attach_function :free_sample_struct, [:pointer], :void
end
ptr = FFISample.create_sample_struct
s = FFISample::SampleStruct.new ptr
puts "i: #{s[:i]}, b:#{s[:b]}, s:#{s[:s]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment