C 编译器
使用低开销从 JavaScript 编译和运行 C 代码
bun:ffi 具有从 JavaScript 以低开销编译和运行 C 代码的实验性支持。
使用方法(bun:ffi 中的 cc)
有关背景信息,请参阅介绍性博客文章。
JavaScript 代码:
import { cc } from "bun:ffi";
import source from "./hello.c" with { type: "file" };
const {
symbols: { hello },
} = cc({
source,
symbols: {
hello: {
args: [],
returns: "int",
},
},
});
console.log("宇宙的答案是什么?", hello());
C 源代码:
int hello() {
return 42;
}
运行 hello.ts 会输出:
bun hello.ts
What is the answer to the universe? 42
cc 使用 TinyCC 编译 C 代码,然后将其与 JavaScript 运行时链接,并在原地转换类型。
基本类型
cc 支持与 dlopen 相同的 FFIType 值,但不包括 buffer_length。只有 cc 支持 napi_env 和 napi_value。
FFIType | C 类型 | 别名 |
|---|---|---|
| buffer | char* | |
| cstring | char* | |
| function | (void*)(*)() | fn, callback |
| ptr | void* | pointer, void*, char* |
| i8 | int8_t | int8_t |
| i16 | int16_t | int16_t |
| i32 | int32_t | int32_t, int |
| i64 | int64_t | int64_t, isize |
| i64_fast | int64_t | |
| u8 | uint8_t | uint8_t |
| u16 | uint16_t | uint16_t |
| u32 | uint32_t | uint32_t |
| u64 | uint64_t | uint64_t, usize |
| u64_fast | uint64_t | |
| f32 | float | float |
| f64 | double | double |
| bool | bool | |
| char | char | |
| napi_env | napi_env | |
| napi_value | napi_value |
字符串、对象及非基本类型
对于无法与 C 类型一一对应的字符串、对象和其他非基本类型,cc 支持 N-API。
使用 napi_value 可以在 C 函数中传递或接收 JavaScript 值,而无需进行任何类型转换。
你也可以传递一个 napi_env,用以接收调用 JavaScript 函数时使用的 N-API 环境。
从 C 返回字符串到 JavaScript
例如,从 C 向 JavaScript 返回字符串:
import { cc } from "bun:ffi";
import source from "./hello.c" with { type: "file" };
const {
symbols: { hello },
} = cc({
source,
symbols: {
hello: {
args: ["napi_env"],
returns: "napi_value",
},
},
});
const result = hello();
对应的 C 代码:
#include <node/node_api.h>
napi_value hello(napi_env env) {
napi_value result;
napi_create_string_utf8(env, "Hello, Napi!", NAPI_AUTO_LENGTH, &result);
return result;
}
同样的方法也可以返回对象和数组等其他类型:
#include <node/node_api.h>
napi_value hello(napi_env env) {
napi_value result;
napi_create_object(env, &result);
return result;
}
cc 参考文档
library: string | string[]
使用 library 指定要与 C 代码链接的库。
type Library = string | string[];
cc({
source: "hello.c",
library: ["sqlite3"],
});
symbols
使用 symbols 对象来指定要暴露给 JavaScript 的函数和变量。
type Symbols = {
[key: string]: {
args: FFIType[];
returns: FFIType;
};
};
source
source 是要编译并与 JavaScript 运行时链接的 C 代码路径。
type Source = string | URL | BunFile;
cc({
source: "hello.c",
symbols: {
hello: {
args: [],
returns: "int",
},
},
});
flags: string | string[]
flags 是传递给 TinyCC 编译器的可选字符串或字符串数组。
type Flags = string | string[];
这些是类似 -I 指定包含目录和 -D 预处理定义的标志。
define: Record<string, string>
define 是传递给 TinyCC 编译器的可选预处理器定义对象。
type Defines = Record<string, string>;
cc({
source: "hello.c",
define: {
NDEBUG: "1",
},
});
禁用 cc
传递 --no-ffi-cc 可为进程禁用 C 编译器。此后,任何对 cc() 的调用都会抛出代码为 ERR_FFI_CC_DISABLED 的错误。--no-addons 标志也会禁用 cc(),此外还会禁用 process.dlopen。
bun --no-ffi-cc ./app.ts
Worker 会继承其父级的设置。Worker 也可以使用 execArgv: ["--no-ffi-cc"] 为自身设置此选项。可以通过 bun build --compile --compile-exec-argv="--no-ffi-cc" 将此选项嵌入独立可执行文件。