开始使用
对koffi的简单了解
安装
你可以使用 npm 安装 Koffi:
npm install koffi
安装 Koffi 后,您可以开始加载它:
// CommonJS syntax
const koffi = require('koffi');
// ES6 modules
import koffi from 'koffi';
案例
您可以在下面找到两个示例:
第一个在 Linux 上运行。这些函数是用类似 C 的原型语言声明的。
第二个运行在 Windows 上,并使用类似 node-ffi 的语法来声明函数。
对于 Linux
这是 Linux 系统的一个小示例,它使用gettimeofday()
,localtime_r()
和printf()
来打印当前时间。
它说明了输出参数的使用。
// ES6 syntax: import koffi from 'koffi';
const koffi = require('koffi');
// Load the shared library
const lib = koffi.load('libc.so.6');
// Declare struct types
const timeval = koffi.struct('timeval', {
tv_sec: 'unsigned int',
tv_usec: 'unsigned int'
});
const timezone = koffi.struct('timezone', {
tz_minuteswest: 'int',
tz_dsttime: 'int'
});
const time_t = koffi.struct('time_t', { value: 'int64_t' });
const tm = koffi.struct('tm', {
tm_sec: 'int',
tm_min: 'int',
tm_hour: 'int',
tm_mday: 'int',
tm_mon: 'int',
tm_year: 'int',
tm_wday: 'int',
tm_yday: 'int',
tm_isdst: 'int'
});
// Find functions
const gettimeofday = lib.func('int gettimeofday(_Out_ timeval *tv, _Out_ timezone *tz)');
const localtime_r = lib.func('tm *localtime_r(const time_t *timeval, _Out_ tm *result)');
const printf = lib.func('int printf(const char *format, ...)');
// Get local time
let tv = {};
let now = {};
gettimeofday(tv, null);
localtime_r({ value: tv.tv_sec }, now);
// And format it with printf (variadic function)
printf('Hello World!\n');
printf('Local time: %02d:%02d:%02d\n', 'int', now.tm_hour, 'int', now.tm_min, 'int', now.tm_sec);
对于 Windows
这是一个针对 Win32 API 的小示例,用于MessageBox()
显示Hello World!给用户的消息。
它说明了 x86 stdcall 调用约定的使用以及 UTF-8 和 UTF-16 字符串参数的使用。
// ES6 syntax: import koffi from 'koffi';
const koffi = require('koffi');
// Load the shared library
const lib = koffi.load('user32.dll');
// Declare constants
const MB_OK = 0x0;
const MB_YESNO = 0x4;
const MB_ICONQUESTION = 0x20;
const MB_ICONINFORMATION = 0x40;
const IDOK = 1;
const IDYES = 6;
const IDNO = 7;
// Find functions
const MessageBoxA = lib.func('__stdcall', 'MessageBoxA', 'int', ['void *', 'str', 'str', 'uint']);
const MessageBoxW = lib.func('__stdcall', 'MessageBoxW', 'int', ['void *', 'str16', 'str16', 'uint']);
let ret = MessageBoxA(null, 'Do you want another message box?', 'Koffi', MB_YESNO | MB_ICONQUESTION);
if (ret == IDYES)
MessageBoxW(null, 'Hello World!', 'Koffi', MB_ICONINFORMATION);
Last updated