-
Notifications
You must be signed in to change notification settings - Fork 62
FFI Library
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:
For simple usage examples, you may also look at the FFI library tests
// 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:
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);