Skip to content
Maxime Chevalier-Boisvert edited this page Feb 18, 2015 · 4 revisions

The FFI library (lib/ffi.js) provides tools to interface with C libraries. It allows calling into C functions and manipulating types such as C strings, structs and unions.

This tutorial demonstrates basic usage: http://tach4n.wordpress.com/2013/09/19/higgs-ffi-calling-c-from-js/

For examples of real-world libraries interfaced using the FFI, see:

  • stdio (C stdio)
  • stdlib (C stdlib)
  • dir (directory traversal)
  • x11 (X windows library)

For simple usage examples, you may also look at the FFI library tests

Interfacing with C Structs

// First import the FFI library
var ffi = require('lib/ffi');

// Declaring a struct type
ffi.c.cdef(`
    struct MyStruct
    {
        float a;
        int b;
        char c;
    };
`);

// To allocate a struct of a given type
var myStruct = ffi.c.MyStruct();

// Members can be accessed with getter and setter functions
var a = myStruct.get_a();
myStruct.set_b(42);

// All structs allocated by Higgs are allocated with C malloc
// You can get the pointer to a struct instance as follows:
var ptr = myStruct.ptr;

// To get the size of a struct type instance
var size = ffi.c.ctypes['struct MyStruct'];

Note that unions are interfaced in an identical way to structs.

For a deeper understanding of C structs, I recommend the following resources:

C Strings

JavaScript and C strings are not the same. The strings allocated by Higgs are in UTF-16 format and are allocated within Higgs' own garbage-collected heap. C strings are raw pointers to manually allocated memory. As such, if you want to pass JS strings to C and vice versa, it is necessary to convert between the two formats.

var ffi = require('lib/ffi');

// This converts a JS string to a C string
// The C string is allocated with malloc
var cStr = ffi.cstr('foo');

// This converts a C string into a JS string
var jsStr = ffi.string(cStr);