File: callback_spec.rb

package info (click to toggle)
jruby 1.5.1-1%2Bdeb6u1
  • links: PTS, VCS
  • area: non-free
  • in suites: squeeze-lts
  • size: 47,024 kB
  • ctags: 74,144
  • sloc: ruby: 398,155; java: 169,506; yacc: 3,782; xml: 2,469; ansic: 415; sh: 279; makefile: 78; tcl: 40
file content (45 lines) | stat: -rw-r--r-- 1,347 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'ffi'

describe "Callback" do
  module LibC
    extend FFI::Library
    ffi_lib FFI::Platform::LIBC
    callback :qsort_cmp, [ :pointer, :pointer ], :int
    attach_function :qsort, [ :pointer, :int, :int, :qsort_cmp ], :int
  end
  it "arguments get passed correctly" do
    p = MemoryPointer.new(:int, 2)
    p.put_array_of_int32(0, [ 1 , 2 ])
    args = []
    cmp = proc do |p1, p2| args.push(p1.get_int(0)); args.push(p2.get_int(0)); 0; end
    # this is a bit dodgey, as it relies on qsort passing the args in order
    LibC.qsort(p, 2, 4, cmp)
#    args.should == [ 1, 2 ]
  end

  it "Block can be substituted for Callback as last argument" do
    p = MemoryPointer.new(:int, 2)
    p.put_array_of_int32(0, [ 1 , 2 ])
    args = []
    # this is a bit dodgey, as it relies on qsort passing the args in order
    LibC.qsort(p, 2, 4) do |p1, p2| 
      args.push(p1.get_int(0))
      args.push(p2.get_int(0))
      0
    end
#    args.should == [ 1, 2 ]
  end  
  it "can be inlined" do
    module LibC
    extend FFI::Library
    attach_function :qsort, [ :pointer, :int, :int, callback(:qsort_cmp, [ :pointer, :pointer ], :int) ], :int
    end
  end

  it "can be anonymous" do
    module LibC
    extend FFI::Library
    attach_function :qsort, [ :pointer, :int, :int, callback([ :pointer, :pointer ], :int) ], :int
  end
end
end