Koffi 自动尝试非标准 x86 调用约定的损坏名称。有关此主题的更多信息,请参阅有关调用约定的部分。
类似 C 的原型
如果您愿意,可以使用简单的类似 C 的原型字符串来声明函数,如下所示
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)');
您可以将()or(void)用于不带参数的函数。
可变参数函数
可变参数函数是用省略号作为最后一个参数来声明的。
为了调用可变参数函数,您必须为每个附加 C 参数提供两个 Javascript 参数,第一个是预期类型,第二个是值。
// 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)');
调用类型
同步调用
一旦声明了本机函数,您就可以像调用任何其他 JS 函数一样简单地调用它。
const atoi = lib.func('int atoi(const char *str)');
let value = atoi('1257');
console.log(value);
下面的示例展示了如何基于以下本机 C 库以两种方式调用 C 函数指针:int (*)(int, int)
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;
}
}