|
| 1 | + |
| 2 | + |
| 3 | +module FFITests |
| 4 | + module CLib |
| 5 | + extend FFI::Library |
| 6 | + |
| 7 | + ffi_lib :c |
| 8 | + |
| 9 | + attach_function :sleep, [:uint32], :uint32 |
| 10 | + end |
| 11 | + |
| 12 | + module TestLib |
| 13 | + extend FFI::Library |
| 14 | + |
| 15 | + ffi_lib '/Users/schmurfy/Dev/personal/mrbgems/mruby-rubyffi-compat/specs/libtest/libtest.dylib' |
| 16 | + |
| 17 | + attach_function :return_uint, [:uint32], :uint32 |
| 18 | + attach_function :return_double, [:double], :double |
| 19 | + attach_function :return_uint_by_address, [:pointer], :void |
| 20 | + |
| 21 | + |
| 22 | + class S1Struct < FFI::Struct |
| 23 | + layout( |
| 24 | + :n1, :uint32, |
| 25 | + :n2, :uint32, |
| 26 | + :s1, :uint16, |
| 27 | + :d1, :double, |
| 28 | + ) |
| 29 | + end |
| 30 | + |
| 31 | + attach_function :fill_struct, [:pointer], :void |
| 32 | + end |
| 33 | +end |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | +should 'return integer by address' do |
| 38 | + n = FFI::MemoryPointer.new(:uint32) |
| 39 | + FFITests::TestLib.return_uint_by_address(n) |
| 40 | + assert_equal(42, n.read_uint32()) |
| 41 | +end |
| 42 | + |
| 43 | +should 'return integer by value' do |
| 44 | + ret = FFITests::TestLib.return_uint(4) |
| 45 | + assert_equal(4, ret) |
| 46 | +end |
| 47 | + |
| 48 | +should 'return double by value' do |
| 49 | + ret = FFITests::TestLib.return_double(4.32) |
| 50 | + assert_equal(4.32, ret) |
| 51 | +end |
| 52 | + |
| 53 | +should 'fill structure' do |
| 54 | + s = FFITests::TestLib::S1Struct.new |
| 55 | + FFITests::TestLib.fill_struct(s.addr) |
| 56 | + |
| 57 | + assert_equal(56, s[:n1]) |
| 58 | + assert_equal(982, s[:n2]) |
| 59 | + assert_equal(12, s[:s1]) |
| 60 | + assert_equal(6.78, s[:d1]) |
| 61 | +end |
| 62 | + |
| 63 | + |
| 64 | +should 'sleep 1s' do |
| 65 | + t = Time.now |
| 66 | + FFITests::CLib.sleep(1) |
| 67 | + assert_equal(1, (Time.now - t).to_i) |
| 68 | +end |
| 69 | + |
0 commit comments