Quick start#

Install Koffi#

You can install Koffi with npm:

1npm install koffi

Once you have installed Koffi, you can start by loading it this way:

1const koffi = require('koffi');

Below you can find three examples:

  • The first one runs on Linux. The functions are declared with the C-like prototype language.

  • The second one runs on Windows, and uses the node-ffi like syntax to declare functions.

Small Linux example#

This is a small example for Linux systems, which uses gettimeofday(), localtime_r() and printf() to print the current time.

It illustrates the use of output parameters.

 1const koffi = require('koffi');
 2
 3// Load the shared library
 4const lib = koffi.load('libc.so.6');
 5
 6// Declare struct types
 7const timeval = koffi.struct('timeval', {
 8    tv_sec: 'unsigned int',
 9    tv_usec: 'unsigned int'
10});
11const timezone = koffi.struct('timezone', {
12    tz_minuteswest: 'int',
13    tz_dsttime: 'int'
14});
15const time_t = koffi.struct('time_t', { value: 'int64_t' });
16const tm = koffi.struct('tm', {
17    tm_sec: 'int',
18    tm_min: 'int',
19    tm_hour: 'int',
20    tm_mday: 'int',
21    tm_mon: 'int',
22    tm_year: 'int',
23    tm_wday: 'int',
24    tm_yday: 'int',
25    tm_isdst: 'int'
26});
27
28// Find functions
29const gettimeofday = lib.func('int gettimeofday(_Out_ timeval *tv, _Out_ timezone *tz)');
30const localtime_r = lib.func('tm *localtime_r(const time_t *timeval, _Out_ tm *result)');
31const printf = lib.func('int printf(const char *format, ...)');
32
33// Get local time
34let tv = {};
35let now = {};
36gettimeofday(tv, null);
37localtime_r({ value: tv.tv_sec }, now);
38
39// And format it with printf (variadic function)
40printf('Hello World!\n');
41printf('Local time: %02d:%02d:%02d\n', 'int', now.tm_hour, 'int', now.tm_min, 'int', now.tm_sec);

Small Windows example#

This is a small example targeting the Win32 API, using MessageBox() to show a Hello World! message to the user.

It illustrates the use of the x86 stdcall calling convention, and the use of UTF-8 and UTF-16 string arguments.

 1const koffi = require('koffi');
 2
 3// Load the shared library
 4const lib = koffi.load('user32.dll');
 5
 6// Declare constants
 7const MB_OK = 0x0;
 8const MB_YESNO = 0x4;
 9const MB_ICONQUESTION = 0x20;
10const MB_ICONINFORMATION = 0x40;
11const IDOK = 1;
12const IDYES = 6;
13const IDNO = 7;
14
15// Find functions
16const MessageBoxA = lib.stdcall('MessageBoxA', 'int', ['void *', 'str', 'str', 'uint']);
17const MessageBoxW = lib.stdcall('MessageBoxW', 'int', ['void *', 'str16', 'str16', 'uint']);
18
19let ret = MessageBoxA(null, 'Do you want another message box?', 'Koffi', MB_YESNO | MB_ICONQUESTION);
20if (ret == IDYES)
21    MessageBoxW(null, 'Hello World!', 'Koffi', MB_ICONINFORMATION);