Skip to content
jacius edited this page Sep 13, 2010 · 3 revisions

How to create a library binding

ffi-swig-generator can only read SWIG-generated XML files. If you have an interface file (.i) or header files (.h), you will first have to convert them to XML using SWIG, then use ffi-swig-generator to convert the XML to Ruby.

You will need to install both SWIG and ffi-swig-generator.

Converting from interface file (.i) to XML

If your library comes with a SWIG interface file (file extension is “.i”), you can easily convert it to XML for use with ffi-swig-generator.

Assuming your interface file is called “mylib.i”, run this command to convert it to XML:
swig -xml -o mylib.xml mylib.i

Converting from header files (.h) to XML

If you only have the header files (file extension is “.h”), it is a big more work to convert it to XML:

  1. Copy all the header files for your target library (the libray you want to create an FFI binding for) to a new directory. This will allow you to safely edit them to help SWIG parse them, if necessary.
  2. Open a terminal/command line window, and cd to the directory where you copied the headers.
  3. Try the following command. It may fail, but its error message will be useful. (Change mylib to the name of your library, and mylib.h to the filename of the main header for your library.)
    swig -includeall -ignoremissing -xml -o mylib.xml -module mylib mylib.h
  4. If there are error messages (you can usually ignore warnings), you may need to edit the header files to change or remove parts of the code, to help SWIG parse it. Edit the files, then try the command above. Or consult the SWIG documentation or an expert.
  5. If there are no error messages, then SWIG succeeded! Your XML file is now ready to be converted with ffi-swig-generator!

If the library is separated into multiple header files that do not #include each other, you will need to repeat this process again for each of the main header files. Be sure to use a separate XML file for each one, so it doesn’t overwrite the previous output.

Converting from XML to Ruby

Once you have created the XML file, ffi-swig-generator can convert it to Ruby code with the following command. If your library is large, this may take a while to complete, so be patient.

ffi-gen mylib.xml mylib.rb

You can then load up mylib.rb in your favorite code editor and start to clean and fix it, for example by creating a module around the contents, and by adding an ffi_lib "mylib" statement, etc.