开始使用

预计阅读时间: 3 分钟

源文档 - Get started

安装 Koffi

你可以通过 npm 安装 Koffi:

npm install koffi

安装完成后,你可以开始加载它:

// CommonJS 语法
const koffi = require("koffi");

// ES6 模块
import koffi from "koffi";

简单示例

以下是两个示例:

  • 第一个示例在 Linux 上运行,使用类似 C 的原型语言声明函数。
  • 第二个示例在 Windows 上运行,使用类似 node-ffi 的语法声明函数。

对于 Linux

这是一个针对 Linux 系统的小示例,使用 gettimeofday()localtime_r()printf() 打印当前时间。

它展示了如何使用输出参数。

// ES6 语法: import koffi from 'koffi';
const koffi = require("koffi");

// 加载共享库
const lib = koffi.load("libc.so.6");

// 声明结构体类型
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",
});

// 查找函数
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, ...)");

// 获取本地时间
let tv = {};
let now = {};
gettimeofday(tv, null);
localtime_r({ value: tv.tv_sec }, now);

// 使用 printf(变参函数)格式化输出
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 语法: import koffi from 'koffi';
const koffi = require("koffi");

// 加载共享库
const lib = koffi.load("user32.dll");

// 声明常量
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;

// 查找函数
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);

打包 Koffi

请阅读专门的页面,了解有关使用 Koffi 打包和打包应用程序的信息。

手动构建

如果你想要自己构建原生 Koffi 代码,请按照构建说明操作。

记录

只有在你想要对 Koffi 进行开发时才需要这样做。官方的 NPM 包提供了预构建的二进制文件,如果你只想在 Node.js 中使用 Koffi,则无需编译任何内容。