v / examples / call_v_from_ruby / test.rb
39 lines · 31 sloc · 976 bytes · fe669f8ce1fabd79754806f1236ad74f605c5bb3
Raw
1require 'bundler/inline'
2
3gemfile do
4 source 'https://rubygems.org'
5 gem 'ffi'
6end
7
8require 'ffi'
9
10# extension for shared libraries varies by platform - see vlib/dl/dl.v
11# get_shared_library_extension()
12def shared_library_extension
13 if Gem.win_platform?
14 '.dll'
15 elsif RUBY_PLATFORM =~ /darwin/ # MacOS
16 '.dylib'
17 else
18 '.so'
19 end
20end
21
22module Lib
23 extend FFI::Library
24
25 begin
26 ffi_lib File.join(File.dirname(__FILE__), 'test' + shared_library_extension)
27 rescue LoadError
28 abort("No shared library test#{shared_library_extension} found. Check examples/call_v_from_ruby/README.md")
29 end
30
31 attach_function :square, [:int], :int
32 attach_function :sqrt_of_sum_of_squares, [:double, :double], :double
33end
34
35puts "Lib.square(10) result is #{Lib.square(10)}"
36raise 'Cannot validate V square().' unless Lib.square(10) == 100
37
38raise 'Cannot validate V sqrt_of_sum_of_squares().' unless \
39 Lib.sqrt_of_sum_of_squares(1.1, 2.2) == Math.sqrt(1.1*1.1 + 2.2*2.2)
40