Module: FFI::Library

Defined in:
lib/ffi/library.rb

Overview

This module is the base to use native functions.

A basic usage may be:

require 'ffi'

module Hello
  extend FFI::Library
  ffi_lib FFI::Library::LIBC
  attach_function 'puts', [ :string ], :int
end

Hello.puts("Hello, World")

Constant Summary

CURRENT_PROCESS =
FFI::CURRENT_PROCESS
LIBC =
FFI::Platform::LIBC
FlagsMap =

Flags used in #ffi_lib.

This map allows you to supply symbols to #ffi_lib_flags instead of the actual constants.

{
  :global => DynamicLibrary::RTLD_GLOBAL,
  :local => DynamicLibrary::RTLD_LOCAL,
  :lazy => DynamicLibrary::RTLD_LAZY,
  :now => DynamicLibrary::RTLD_NOW
}

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (nil) extended(mod)

Test if extended object is a Module. If not, raise RuntimeError.

Parameters:

  • mod

    extended object

Returns:

  • (nil)

Raises:

  • (RuntimeError)

    if mod is not a Module



77
78
79
# File 'lib/ffi/library.rb', line 77

def self.extended(mod)
  raise RuntimeError.new("must only be extended by module") unless mod.kind_of?(Module)
end

Instance Method Details

- (FFI::VariadicInvoker) attach_function(func, args, returns, options = {}) - (FFI::VariadicInvoker) attach_function(name, func, args, returns, options = {})

Attach C function func to this module.

Overloads:

  • - (FFI::VariadicInvoker) attach_function(func, args, returns, options = {})

    Examples:

    attach function without an explicit name

    module Foo
      extend FFI::Library
      ffi_lib FFI::Library::LIBC
      attach_function :malloc, [:size_t], :pointer
    end
    # now callable via Foo.malloc
  • - (FFI::VariadicInvoker) attach_function(name, func, args, returns, options = {})

    Examples:

    attach function with an explicit name

    module Bar
      extend FFI::Library
      ffi_lib FFI::Library::LIBC
      attach_function :c_malloc, :malloc, [:size_t], :pointer
    end
    # now callable via Bar.c_malloc

Parameters:

  • name (#to_s)

    name of ruby method to attach as

  • func (#to_s)

    name of C function to attach

  • args (Array<Symbol>)

    an array of types

  • returns (Symbol) (defaults to: nil)

    type of return value

  • options (Hash) (defaults to: nil)

    a customizable set of options

Options Hash (options):

  • :blocking (Boolean) — default: @blocking

    set to true if the C function is a blocking call

  • :convention (Symbol) — default: :default

    calling convention (see #ffi_convention)

  • :enums (FFI::Enums)
  • :type_map (Hash)

Returns:

Raises:



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/ffi/library.rb', line 210

def attach_function(name, func, args, returns = nil, options = nil)
  mname, a2, a3, a4, a5 = name, func, args, returns, options
  cname, arg_types, ret_type, opts = (a4 && (a2.is_a?(String) || a2.is_a?(Symbol))) ? [ a2, a3, a4, a5 ] : [ mname.to_s, a2, a3, a4 ]

  # Convert :foo to the native type
  arg_types.map! { |e| find_type(e) }
  options = {
    :convention => ffi_convention,
    :type_map => defined?(@ffi_typedefs) ? @ffi_typedefs : nil,
    :blocking => defined?(@blocking) && @blocking,
    :enums => defined?(@ffi_enums) ? @ffi_enums : nil,
  }

  @blocking = false
  options.merge!(opts) if opts && opts.is_a?(Hash)

  # Try to locate the function in any of the libraries
  invokers = []
  ffi_libraries.each do |lib|
    if invokers.empty?
      begin
        function = nil
        function_names(cname, arg_types).find do |fname|
          function = lib.find_function(fname)
        end
        raise LoadError unless function

        invokers << if arg_types.length > 0 && arg_types[arg_types.length - 1] == FFI::NativeType::VARARGS
          VariadicInvoker.new(function, arg_types, find_type(ret_type), options)

        else
          Function.new(find_type(ret_type), arg_types, function, options)
        end

      rescue LoadError
      end
    end
  end
  invoker = invokers.compact.shift
  raise FFI::NotFoundError.new(cname.to_s, ffi_libraries.map { |lib| lib.name }) unless invoker

  invoker.attach(self, mname.to_s)
  invoker
end

- (DynamicLibrary::Symbol) attach_variable(mname, cname, type) - (DynamicLibrary::Symbol) attach_variable(cname, type)

Attach C variable cname to this module.

Overloads:

  • - (DynamicLibrary::Symbol) attach_variable(mname, cname, type)

    Examples:

    module Bar
      extend FFI::Library
      ffi_lib 'my_lib'
      attach_variable :c_myvar, :myvar, :long
    end
    # now callable via Bar.c_myvar
  • - (DynamicLibrary::Symbol) attach_variable(cname, type)

    Examples:

    module Bar
      extend FFI::Library
      ffi_lib 'my_lib'
      attach_variable :myvar, :long
    end
    # now callable via Bar.myvar

Parameters:

  • mname (#to_s)

    name of ruby method to attach as

  • cname (#to_s)

    name of C variable to attach

  • type (DataConverter, Struct, Symbol, Type)

    C varaible's type

Returns:

Raises:



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/ffi/library.rb', line 305

def attach_variable(mname, a1, a2 = nil)
  cname, type = a2 ? [ a1, a2 ] : [ mname.to_s, a1 ]
  address = nil
  ffi_libraries.each do |lib|
    begin
      address = lib.find_variable(cname.to_s)
      break unless address.nil?
    rescue LoadError
    end
  end

  raise FFI::NotFoundError.new(cname, ffi_libraries) if address.nil? || address.null?
  if type.is_a?(Class) && type < FFI::Struct
    # If it is a global struct, just attach directly to the pointer
    s = type.new(address)
    self.module_eval <<-code, __FILE__, __LINE__
      @@ffi_gvar_#{mname} = s
      def self.#{mname}
        @@ffi_gvar_#{mname}
      end
code

  else
    sc = Class.new(FFI::Struct)
    sc.layout :gvar, find_type(type)
    s = sc.new(address)
    #
    # Attach to this module as mname/mname=
    #
    self.module_eval <<-code, __FILE__, __LINE__
      @@ffi_gvar_#{mname} = s
      def self.#{mname}
        @@ffi_gvar_#{mname}[:gvar]
      end
      def self.#{mname}=(value)
        @@ffi_gvar_#{mname}[:gvar] = value
      end
    code

  end

  address
end

- (FFI::CallbackInfo) callback(name, params, ret) - (FFI::CallbackInfo) callback(params, ret)

Parameters:

  • name

    callback name to add to type map

  • params (Array)

    array of parameters' types

  • ret (DataConverter, Struct, Symbol, Type)

    callback return type

Returns:

Raises:

  • (ArgumentError)


356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/ffi/library.rb', line 356

def callback(*args)
  raise ArgumentError, "wrong number of arguments" if args.length < 2 || args.length > 3
  name, params, ret = if args.length == 3
    args
  else
    [ nil, args[0], args[1] ]
  end

  options = Hash.new
  options[:convention] = ffi_convention
  options[:enums] = @ffi_enums if defined?(@ffi_enums)
  cb = FFI::CallbackInfo.new(find_type(ret), params.map { |e| find_type(e) }, options)

  # Add to the symbol -> type map (unless there was no name)
  unless name.nil?
    typedef cb, name
  end

  cb
end

- (FFI::Enum) enum(name, values) - (FFI::Enum) enum(*args) - (FFI::Enum) enum(values)

Create a new Enum.

Overloads:

  • - (FFI::Enum) enum(name, values)

    Create a named enum.

    Examples:

    enum :foo, [:zero, :one, :two]  # named enum

    Parameters:

    • name (Symbol)

      name for new enum

    • values (Array)

      values for enum

  • - (FFI::Enum) enum(*args)

    Create an unnamed enum.

    Examples:

    enum :zero, :one, :two  # unnamed enum

    Parameters:

    • args

      values for enum

  • - (FFI::Enum) enum(values)

    Create an unnamed enum.

    Examples:

    enum [:zero, :one, :two]  # unnamed enum, equivalent to above example

    Parameters:

    • values (Array)

      values for enum

Returns:



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/ffi/library.rb', line 435

def enum(*args)
  name, values = if args[0].kind_of?(Symbol) && args[1].kind_of?(Array)
    [ args[0], args[1] ]
  elsif args[0].kind_of?(Array)
    [ nil, args[0] ]
  else
    [ nil, args ]
  end
  @ffi_enums = FFI::Enums.new unless defined?(@ffi_enums)
  @ffi_enums << (e = FFI::Enum.new(values, name))

  # If called as enum :foo, [ :zero, :one, :two ], add a typedef alias
  typedef(e, name) if name
  e
end

- (FFI::Enum) enum_type(name)

Find an enum by name.

Parameters:

  • name

Returns:



454
455
456
# File 'lib/ffi/library.rb', line 454

def enum_type(name)
  @ffi_enums.find(name) if defined?(@ffi_enums)
end

- (FFI::Enum) enum_value(symbol)

Find an enum by a symbol it contains.

Parameters:

  • symbol

Returns:



461
462
463
# File 'lib/ffi/library.rb', line 461

def enum_value(symbol)
  @ffi_enums.__map_symbol(symbol)
end

- (Symbol) ffi_convention(convention = nil)

Note:

:stdcall is typically used for attaching Windows API functions

Set the calling convention for #attach_function and #callback

Parameters:

  • convention (Symbol) (defaults to: nil)

    one of :default, :stdcall

Returns:

  • (Symbol)

    the new calling convention

See Also:



139
140
141
142
143
# File 'lib/ffi/library.rb', line 139

def ffi_convention(convention = nil)
  @ffi_convention ||= :default
  @ffi_convention = convention if convention
  @ffi_convention
end

- (Array<DynamicLibrary>) ffi_lib(*names)

Load native libraries.

Parameters:

  • names (Array)

    names of libraries to load

Returns:

Raises:

  • (LoadError)

    if a library cannot be opened



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/ffi/library.rb', line 86

def ffi_lib(*names)
  lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL
  ffi_libs = names.map do |name|

    if name == FFI::CURRENT_PROCESS
      FFI::DynamicLibrary.open(nil, FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL)

    else
      libnames = (name.is_a?(::Array) ? name : [ name ]).map { |n| [ n, FFI.map_library_name(n) ].uniq }.flatten.compact
      lib = nil
      errors = {}

      libnames.each do |libname|
        begin
          lib = FFI::DynamicLibrary.open(libname, lib_flags)
          break if lib

        rescue Exception => ex
          ldscript = false
          if ex.message =~ /(([^ \t()])+\.so([^ \t:()])*):([ \t])*invalid ELF header/
            if File.read($1) =~ /GROUP *\( *([^ \)]+) *\)/
              libname = $1
              ldscript = true
            end
          end

          if ldscript
            retry
          else
            errors[libname] = ex
          end
        end
      end

      if lib.nil?
        raise LoadError.new(errors.values.join(".\n"))
      end

      # return the found lib
      lib
    end
  end

  @ffi_libs = ffi_libs
end

- (Fixnum) ffi_lib_flags(*flags)

Sets library flags for #ffi_lib.

Examples:

ffi_lib_flags(:lazy, :local) # => 5

Parameters:

  • flags (Symbol, )

    (see FlagsMap)

Returns:

  • (Fixnum)

    the new value



172
173
174
# File 'lib/ffi/library.rb', line 172

def ffi_lib_flags(*flags)
  @ffi_lib_flags = flags.inject(0) { |result, f| result | FlagsMap[f] }
end

- (Array<FFI::DynamicLibrary>) ffi_libraries

Get FFI libraries loaded using #ffi_lib.

Returns:

Raises:

  • (LoadError)

    if no libraries have been loaded (using #ffi_lib)

See Also:



149
150
151
152
# File 'lib/ffi/library.rb', line 149

def ffi_libraries
  raise LoadError.new("no library specified") if !defined?(@ffi_libs) || @ffi_libs.empty?
  @ffi_libs
end

- (Type) find_type(t)

Find a type definition.

Parameters:

Returns:



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/ffi/library.rb', line 468

def find_type(t)
  if t.kind_of?(Type)
    t

  elsif defined?(@ffi_typedefs) && @ffi_typedefs.has_key?(t)
    @ffi_typedefs[t]

  elsif t.is_a?(Class) && t < Struct
    Type::POINTER

  elsif t.is_a?(DataConverter)
    # Add a typedef so next time the converter is used, it hits the cache
    typedef Type::Mapped.new(t), t

  end || FFI.find_type(t)
end

- (Array<String>) function_names(name, arg_types)

Note:

Function names on windows may be decorated if they are using stdcall. See

Note that decorated names can be overridden via def files. Also note that the windows api, although using, doesn't have decorated names.

This function returns a list of possible names to lookup.

Parameters:

  • name (#to_s)

    function name

  • arg_types (Array)

    function's argument types

Returns:

  • (Array<String>)


265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/ffi/library.rb', line 265

def function_names(name, arg_types)
  result = [name.to_s]
  if ffi_convention == :stdcall
    # Get the size of each parameter
    size = arg_types.inject(0) do |mem, arg|
      mem + arg.size
    end

    # Next, the size must be a multiple of 4
    size += (4 - size) % 4

    result << "_#{name.to_s}@#{size}" # win32
    result << "#{name.to_s}@#{size}" # win64
  end
  result
end

- (FFI::Enum, FFI::Type) typedef(old, add, info = nil)

Register or get an already registered type definition.

To register a new type definition, old should be a Type. add is in this case the type definition.

If old is a DataConverter, a Type::Mapped is returned.

If old is :enum

  • and add is an Array, a call to #enum is made with add as single parameter;

  • in others cases, info is used to create a named enum.

If old is a key for type map, #typedef get old type definition.

Parameters:

Returns:



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/ffi/library.rb', line 393

def typedef(old, add, info=nil)
  @ffi_typedefs = Hash.new unless defined?(@ffi_typedefs)

  @ffi_typedefs[add] = if old.kind_of?(FFI::Type)
    old

  elsif @ffi_typedefs.has_key?(old)
    @ffi_typedefs[old]

  elsif old.is_a?(DataConverter)
    FFI::Type::Mapped.new(old)

  elsif old == :enum
    if add.kind_of?(Array)
      self.enum(add)
    else
      self.enum(info, add)
    end

  else
    FFI.find_type(old)
  end
end