make-moonbit-c-bindings

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Make MoonBit C Bindings

构建MoonBit C绑定

Use this skill for end-to-end binding projects. Also read
moonbit-c-binding
before implementation for low-level FFI syntax, ownership annotations, and
moonbit.h
details.
本技能适用于端到端的绑定项目。在实现前,请先阅读
moonbit-c-binding
文档,了解底层FFI语法、所有权注解以及
moonbit.h
的详细信息。

Quick Start

快速开始

  1. Clone or inspect the upstream C/C++ project in a temporary directory.
  2. Identify the public header(s), generated config headers, source layout, allocator API, and build-time type widths.
  3. Decide the safe MoonBit API surface; do not mechanically expose every C API.
  4. Vendor sources with
    templates/prepare.py
    or link to a system library only when that is explicitly desired.
  5. Write a thin C wrapper, private MoonBit externs, and safe public MoonBit wrappers.
  6. Validate with
    moon check
    , native tests, ASan,
    moon info
    , and vendoring script idempotency.
  1. 在临时目录中克隆或调研上游C/C++项目。
  2. 识别公开头文件、生成的配置头文件、源码结构、分配器API以及编译期类型宽度。
  3. 确定安全的MoonBit API接口;不要机械地暴露所有C API。
  4. 使用
    templates/prepare.py
    引入源码(vendor),仅在明确需要时才链接到系统库。
  5. 编写轻量C包装器、私有MoonBit extern声明以及安全的公开MoonBit包装器。
  6. 通过
    moon check
    、原生测试、ASan、
    moon info
    以及引入脚本的幂等性进行验证。

Binding Architecture

绑定架构

Prefer this layout, adapting names to the library. Start from bundled templates instead of rewriting scaffolding from scratch:
text
scripts/prepare.py          # optional: pinned upstream download + generated stubs
moon.mod.json               # preferred/supported native targets
src/moon.pkg                # native-stub list and file target gates
src/wrapper.c               # ABI normalization and ownership boundaries
src/ffi.mbt                 # private extern "c" declarations
src/<domain>.mbt            # safe public MoonBit API
src/<domain>_test.mbt       # regression tests
src/README.mbt.md           # tested documentation examples
README.md -> src/README.mbt.md
Template mapping:
  • templates/prepare.py
    ->
    scripts/prepare.py
  • templates/moon.mod.json
    ->
    moon.mod.json
  • templates/moon.pkg
    ->
    src/moon.pkg
  • templates/wrapper.c
    ->
    src/wrapper.c
  • templates/ffi.mbt
    ->
    src/ffi.mbt
  • templates/api.mbt
    ->
    src/<domain>.mbt
  • templates/README.mbt.md
    ->
    src/README.mbt.md
For ASan validation, copy or invoke the companion runner from
moonbit-c-binding/scripts/run-asan.py
as
scripts/run-asan.py
; do not invent a new ASan patching script unless that runner cannot fit the project.
推荐采用以下布局,可根据库的名称调整命名。从捆绑的模板开始,而非从头编写脚手架:
text
scripts/prepare.py          # 可选:固定版本的上游下载 + 生成的桩代码
moon.mod.json               # 首选/支持的原生目标
src/moon.pkg                # native-stub列表和文件目标门控
src/wrapper.c               # ABI标准化和所有权边界
src/ffi.mbt                 # 私有extern "c"声明
src/<domain>.mbt            # 安全的公开MoonBit API
src/<domain>_test.mbt       # 回归测试
src/README.mbt.md           # 带测试的文档示例
README.md -> src/README.mbt.md
模板映射:
  • templates/prepare.py
    ->
    scripts/prepare.py
  • templates/moon.mod.json
    ->
    moon.mod.json
  • templates/moon.pkg
    ->
    src/moon.pkg
  • templates/wrapper.c
    ->
    src/wrapper.c
  • templates/ffi.mbt
    ->
    src/ffi.mbt
  • templates/api.mbt
    ->
    src/<domain>.mbt
  • templates/README.mbt.md
    ->
    src/README.mbt.md
对于ASan验证,请复制或调用
moonbit-c-binding/scripts/run-asan.py
中的配套运行器,将其保存为
scripts/run-asan.py
;除非该运行器无法适配项目,否则不要自行编写新的ASan补丁脚本。

Workflow

工作流程

1. Survey Upstream

1. 调研上游

  • Read public headers first; they define the binding contract.
  • Record configured widths for project-specific typedefs: index types, scalar types, size/count types, handle types, enum backing types, and callbacks.
  • Separate library APIs from CLI-only, internal, generated, or test code.
  • Look for functions that allocate memory, mutate inputs, store callbacks, or require paired
    destroy/free
    calls.
  • 首先阅读公开头文件;它们定义了绑定契约。
  • 记录项目特定typedef的配置宽度:索引类型、标量类型、大小/计数类型、句柄类型、枚举底层类型以及回调函数。
  • 将库API与仅CLI可用、内部、生成或测试代码区分开。
  • 寻找那些分配内存、修改输入、存储回调或需要配对
    destroy/free
    调用的函数。

2. Design The MoonBit API

2. 设计MoonBit API

  • Expose domain-specific MoonBit types that match the current C library instead of raw pointers and arrays where possible.
  • Validate shapes and option lengths before entering C.
  • Omit unsafe or misleading C features when the safe wrapper cannot uphold their semantics.
  • Map C status codes into MoonBit errors; return structured result records for output parameters.
  • 尽可能暴露与当前C库匹配的领域特定MoonBit类型,而非原始指针和数组。
  • 在进入C层之前验证形状和选项长度。
  • 当安全包装器无法维持某些C特性的语义时,省略不安全或易误导的C特性。
  • 将C状态码映射为MoonBit错误;为输出参数返回结构化结果记录。

3. Vendor Or Link

3. 引入或链接

  • For portable packages, vendor C sources into
    native-stub
    with a pinned revision and a repeatable script.
  • Flatten sources if MoonBit requires stubs in one package directory, and rewrite includes deterministically.
  • Generate configured headers instead of relying on ad hoc compiler flags.
  • Ensure the vendoring script can be rerun with no tracked diff.
  • 对于可移植包,使用固定版本和可重复执行的脚本将C源码引入
    native-stub
  • 如果MoonBit要求桩代码位于一个包目录中,请扁平化源码并确定性地重写包含语句。
  • 生成配置头文件,而非依赖临时编译器标志。
  • 确保引入脚本可重复运行且不会产生已跟踪的差异。

4. Build The FFI Boundary

4. 构建FFI边界

  • C wrapper owns ABI normalization: type-width assertions, optional pointer conversion, output copying, and freeing C-allocated memory.
  • ffi.mbt
    should keep externs private and use
    #borrow
    /
    #owned
    explicitly.
  • Public MoonBit files should call only safe wrapper functions, never raw C APIs.
  • Avoid extra Boolean sentinel parameters for optional arrays; prefer empty MoonBit arrays and check
    Moonbit_array_length
    in C.
  • C包装器负责ABI标准化:类型宽度断言、可选指针转换、输出复制以及释放C分配的内存。
  • ffi.mbt
    应保持extern私有,并显式使用
    #borrow
    /
    #owned
  • 公开的MoonBit文件应仅调用安全的包装器函数,绝不直接调用原始C API。
  • 避免为可选数组添加额外的布尔标记参数;首选空MoonBit数组,并在C层中检查
    Moonbit_array_length

5. Validate

5. 验证

Run, at minimum:
bash
moon fmt
moon check --target all --warn-list +73
moon test --target native
python3 scripts/run-asan.py
moon info --target native
python3 scripts/prepare.py
git status --short
For native-only packages, set
"preferred-target": "native"
and the smallest true
"supported-targets"
value in
moon.mod.json
.
至少运行以下命令:
bash
moon fmt
moon check --target all --warn-list +73
moon test --target native
python3 scripts/run-asan.py
moon info --target native
python3 scripts/prepare.py
git status --short
对于仅原生包,请在
moon.mod.json
中设置
"preferred-target": "native"
以及最小的有效
"supported-targets"
值。

Required References

必备参考资料

Lifecycle And Ownership; Vendoring And Package Setup; Testing And Documentation.
生命周期与所有权源码引入与包设置测试与文档