> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# C 编译器

> 以低开销从 JavaScript 编译和运行 C 代码

`bun:ffi` 具有实验性的支持，可从 JavaScript 以低开销编译和运行 C 代码。

***

## 用法（`bun:ffi` 中的 cc）

有关背景信息，请参见[介绍博客文章](https://bun.com/blog/compile-and-run-c-in-js)。

JavaScript：

```ts hello.ts icon="file-code" theme={null}
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("What is the answer to the universe?", hello());
```

C 源码：

```c hello.c theme={null}
int hello() {
  return 42;
}
```

运行 `hello.ts` 输出：

```sh terminal icon="terminal" theme={null}
bun hello.ts
What is the answer to the universe? 42
```

`cc` 使用 [TinyCC](https://bellard.org/tcc/) 编译 C 代码，然后将其与 JavaScript 运行时链接，原地转换类型。

### 基本类型

`cc` 支持与 [`dlopen`](/runtime/ffi) 相同的 `FFIType` 值。

| `FFIType`   | C 类型           | 别名                        |
| ----------- | -------------- | ------------------------- |
| 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`                 |
| i64\_fast   | `int64_t`      |                           |
| u8          | `uint8_t`      | `uint8_t`                 |
| u16         | `uint16_t`     | `uint16_t`                |
| u32         | `uint32_t`     | `uint32_t`                |
| u64         | `uint64_t`     | `uint64_t`                |
| 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 环境。

#### 向 JavaScript 返回 C 字符串

例如，要从 C 向 JavaScript 返回一个字符串：

```ts hello.ts theme={null}
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 中：

```c hello.c theme={null}
#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;
}
```

同样的方法可以返回其他类型，如对象和数组：

```c hello.c theme={null}
#include <node/node_api.h>

napi_value hello(napi_env env) {
  napi_value result;
  napi_create_object(env, &result);
  return result;
}
```

### `cc` 参考

#### `library: string[]`

使用 `library` 数组指定要与 C 代码链接的库。

```ts theme={null}
type Library = string[];

cc({
  source: "hello.c",
  library: ["sqlite3"],
});
```

#### `symbols`

使用 `symbols` 对象指定要暴露给 JavaScript 的函数和变量。

```ts theme={null}
type Symbols = {
  [key: string]: {
    args: FFIType[];
    returns: FFIType;
  };
};
```

#### `source`

`source` 是要编译并与 JavaScript 运行时链接的 C 代码路径。

```ts theme={null}
type Source = string | URL | BunFile;

cc({
  source: "hello.c",
  symbols: {
    hello: {
      args: [],
      returns: "int",
    },
  },
});
```

#### `flags: string | string[]`

`flags` 是传递给 TinyCC 编译器的可选字符串数组。

```ts theme={null}
type Flags = string | string[];
```

这些是像 `-I`（用于包含目录）和 `-D`（用于预处理器定义）这样的标志。

#### `define: Record<string, string>`

`define` 是传递给 TinyCC 编译器的可选预处理器定义对象。

```ts theme={null}
type Defines = Record<string, string>;

cc({
  source: "hello.c",
  define: {
    NDEBUG: "1",
  },
});
```
