koffi中文
  • KOFFI
  • koffi性能
  • 中文更新日志
  • 安装需求
  • 开始使用
  • 函数调用
  • 输入参数
  • 数据指针
  • 输出参数
  • 多态参数
  • Union数据
  • 导出的变量
  • JAVASCRIPT 回调
  • 杂项
  • 构建工具和koffi
  • 贡献
  • 变更日志
  • 迁移指南
Powered by GitBook
On this page
  • 变量定义
  • 解码为 JS 值
  • 编码到C内存

导出的变量

PreviousUnion数据NextJAVASCRIPT 回调

Last updated 1 year ago

变量定义

Koffi 2.6 中的新功能

要查找导出的变量并声明变量,请使用lib.symbol(name, type)。您需要指定其名称和类型。

int my_int = 42;
const char *my_string = NULL;
const my_int = lib.symbol('my_int', 'int');
const my_string = lib.symbol('my_string', 'const char *');

您不能直接操作这些变量,请使用:

  • 读取它们的值

  • 改变它们的值

解码为 JS 值

Koffi 2.2 中的新增功能,Koffi 2.3 中的更改

用于koffi.decode()解码 C 指针,包装为外部对象或简单数字。

有些参数是可选的,可以通过多种方式调用该函数:

  • koffi.decode(value, type):无偏移

  • koffi.decode(value, offset, type):解码前添加到指针的显式偏移量

默认情况下,Koffi 在解码字符串时期望以 NUL 结尾的字符串。如果您需要指定字符串长度,请参见下文。

以下示例说明如何解码整数和 C 字符串变量。

int my_int = 42;
const char *my_string = "foobar";
const my_int = lib.symbol('my_int', 'int');
const my_string = lib.symbol('my_string', 'const char *');

console.log(koffi.decode(my_int, 'int')) // Prints 42
console.log(koffi.decode(my_string, 'const char *')) // Prints "foobar"

还有一个可选的结束length参数,您可以在两种情况下使用:

  • 使用它给出 non-NUL 终止字符串中要解码的字节数:koffi.decode(value, 'char *', 5)。

  • 将连续值解码为数组。例如,以下是如何解码具有 3 个浮点值的数组:koffi.decode(value, 'float', 3)。这相当于koffi.decode(value, koffi.array('float', 3))。

下面的示例将解码上面定义的符号my_string,但仅解码前三个字节。

// Only decode 3 bytes from the C string my_string
console.log(koffi.decode(my_string, 'const char *', 3)) // Prints "foo"

在Koffi 2.2及更早版本中,length参数仅用于解码字符串,否则被忽略。

编码到C内存

Koffi 2.6 中的新功能

用于koffi.encode()将 JS 值编码为 C 符号或指针,包装为外部对象或简单数字。

有些参数是可选的,可以通过多种方式调用该函数:

  • koffi.encode(ref, type, value):无偏移

  • koffi.encode(ref, offset, type, value):编码前添加到指针的显式偏移量

我们将重用上面显示的示例并使用koffi.encode()更改变量值。

int my_int = 42;
const char *my_string = NULL;
const my_int = lib.symbol('my_int', 'int');
const my_string = lib.symbol('my_string', 'const char *');

console.log(koffi.decode(my_int, 'int')) // Prints 42
console.log(koffi.decode(my_string, 'const char *')) // Prints null

koffi.encode(my_int, 'int', -1);
koffi.encode(my_string, 'const char *', 'Hello World!');

console.log(koffi.decode(my_int, 'int')) // Prints -1
console.log(koffi.decode(my_string, 'const char *')) // Prints "Hello World!"

当编码字符串(直接或嵌入数组或结构中)时,内存将绑定到原始指针值并由 Koffi 管理。您可以一次又一次地分配给同一个字符串,而不会出现任何泄漏或释放后使用的风险。

还有一个可选的结束length参数,可用于对数组进行编码。例如,以下是如何使用 3 个浮点值对数组进行编码:koffi.encode(symbol, 'float', [1, 2, 3], 3)。这相当于koffi.encode(symbol, koffi.array('float', 3), [1, 2, 3])。

在 Koffi 2.6.11 之前,长度参数无法正常工作。

koffi.decode()
koffi.encode()