Subject:
[ruby-ffi] Re: How to copy a struct?
From:
cootcraig
Date:
10/27/11 10:45 AM
To:
ruby-ffi

I think this will work for me.  I use a similar Raw class as buffer
for my DLL call.  I then cast the Raw instance to an appropriate
struct.


#============================= copy_test.rb
require 'ffi'
class Raw < FFI::Struct
  layout :data, [:uchar, 3*4]
  def copy
    r2 = self.class.new
    (0...(self.size)).each {|i| r2[:data][i] = self[:data][i]}
    r2
  end
end
class Ints < FFI::Struct
  layout :f1, :int, :f2, :int, :f3, :int
end

i1 = Ints.new
i1[:f1] = 97
i1[:f2] = 98
i1[:f3] = 99
r1 = Raw.new i1.to_ptr
r2 = r1.copy
i2 = Ints.new r2.to_ptr
puts "#{i2[:f1]} #{i2[:f2]} #{i2[:f3]}"
#=> 97 98 99
puts "i1.to_ptr #{i1.to_ptr} i2.to_ptr #{i2.to_ptr}"
#=> i1.to_ptr #<FFI::MemoryPointer address=0x62e688 size=12> i2.to_ptr
#<FFI::MemoryPointer address=0x62e670 size=12>