constoptions={lazy:true// Use RTLD_LAZY (lazy-binding) on POSIX platforms (by default, use RTLD_NOW)};constlib=koffi.load('/path/to/shared/library.so',options);
如果需要,可以添加更多选项。
函数定义
定义语法
使用 返回的对象koffi.load()从库中加载 C 函数。为此,您可以使用两种语法:
经典语法,灵感来自node-ffi
类 C 原型
经典语法
要声明函数,您需要指定其未损坏的名称、返回类型和参数。使用省略号作为可变参数函数的最后一个参数。
Koffi 自动尝试非标准 x86 调用约定的损坏名称。有关此主题的更多信息,请参阅有关调用约定的部分。
类似 C 的原型
如果您愿意,可以使用简单的类似 C 的原型字符串来声明函数,如下所示
您可以将()or(void)用于不带参数的函数。
可变参数函数
可变参数函数是用省略号作为最后一个参数来声明的。
为了调用可变参数函数,您必须为每个附加 C 参数提供两个 Javascript 参数,第一个是预期类型,第二个是值。
在 x86 平台上,只有 Cdecl 约定可用于可变参数函数。
调用约定(Calling conventions)
Koffi 2.7 中已更改
默认情况下,调用 C 函数是同步发生的。
大多数体系结构每个进程仅支持一种过程调用标准。32 位 x86 平台是一个例外,Koffi 支持多种 x86 约定
const printf = lib.func('int printf(const char *fmt, ...)');
// The parameter name is not used by Koffi, and optional
const atoi = lib.func('int atoi(str)');
// ES6 syntax: import koffi from 'koffi';
const koffi = require('koffi');
const lib = koffi.load('user32.dll');
// The following two declarations are equivalent, and use stdcall on x86 (and the default ABI on other platforms)
const MessageBoxA_1 = lib.func('__stdcall', 'MessageBoxA', 'int', ['void *', 'str', 'str', 'uint']);
const MessageBoxA_2 = lib.func('int __stdcall MessageBoxA(void *hwnd, str text, str caption, uint type)');
const atoi = lib.func('int atoi(const char *str)');
let value = atoi('1257');
console.log(value);
typedef int BinaryIntFunc(int a, int b);
static int AddInt(int a, int b) { return a + b; }
static int SubstractInt(int a, int b) { return a - b; }
BinaryIntFunc *GetBinaryIntFunction(const char *type)
{
if (!strcmp(type, "add")) {
return AddInt;
} else if (!strcmp(type, "substract")) {
return SubstractInt;
} else {
return NULL;
}
}
// Declare function type
const BinaryIntFunc = koffi.proto('int BinaryIntFunc(int a, int b)');
const GetBinaryIntFunction = lib.func('BinaryIntFunc *GetBinaryIntFunction(const char *name)');
const add_ptr = GetBinaryIntFunction('add');
const substract_ptr = GetBinaryIntFunction('substract');
let sum = koffi.call(add_ptr, BinaryIntFunc, 4, 5);
let delta = koffi.call(substract_ptr, BinaryIntFunc, 100, 58);
console.log(sum, delta); // Prints 9 and 42
// Declare function type
const BinaryIntFunc = koffi.proto('int BinaryIntFunc(int a, int b)');
const GetBinaryIntFunction = lib.func('BinaryIntFunc *GetBinaryIntFunction(const char *name)');
const add = koffi.decode(GetBinaryIntFunction('add'), BinaryIntFunc);
const substract = koffi.decode(GetBinaryIntFunction('substract'), BinaryIntFunc);
let sum = add(4, 5);
let delta = substract(100, 58);
console.log(sum, delta); // Prints 9 and 42