FFI: Rubinius' Foreign Function Interface

This section is highly underdeveloped.

Overview

To do.

Usage

The main interface function to FFI is Module#attach_foreign. Extracted documentation on its usage is below:

Module#attach_foreign

Create a wrapper to a function in a C-linked library that exists somewhere in the system. If a specific library is not given, the function is assumed to exist in the running process, the Rubinius executable. The process contains many linked libraries in addition to Rubinius' codebase, libc of course the most prominent on the system side. The wrapper method is added to the Module as a singleton method or a "class method."

The function is specified like a declaration: the first argument is the type symbol for the return type (see FFI documentation for types), the second argument is the name of the function and the third argument is an Array of the types of the function's arguments. Currently at most 6 arguments can be given.

   # If you want to wrap this function:
   int foobar(double arg_one, const char* some_string);
  
   # The arguments to #attach_foreign look like this:
   :int, 'foobar', [:double, :string]

If the function is from an external library such as, say, libpcre, libcurl etc. you can give the name or path of the library. The fourth argument is an option hash and the library name should be given in the +:from+ key of the hash. The name may (and for portable code, should) omit the file extension. If the extension is present, it must be the correct one for the runtime platform. The library is searched for in the system library paths but if necessary, the full absolute or relative path can be given.

By default, the new method's name is the same as the function it wraps but in some cases it is desirable to change this. You can specify the method name in the +:as+ key of the option hash. So if you for whatever reason wanted to import the char* secret(double seed, double watermelon) function from a secret library into your class but name it something else (it is secret, after all,) the entire invocation looks like this:

  class TotallyNotSecretClass
    attach_foreign     :string,  :secret,[:double, :double],     :from => "libsecret", :as => :completely_public
  end

  TotallyNotSecretClass.completely_public   # => _Whatever it is supposed to do_

The "styling" is completely optional and if you prefer, you can use Symbols for the names (except the library name) instead of Strings. I like to make it look as much like the C declaration as possible, hence the indentation.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

0.1069% complete

 

Completed 9 of 13 tickets