Logo vun Moonbit C Binding

Moonbit C Binding

Organisatioun
moonbitlang
moonbit-c-binding

Guide for writing MoonBit bindings to C libraries using native FFI. Use when adding extern "c" declarations, writing C stubs with moonbit.h, configuring native-stub and link.native in moon.pkg, choosing

Iwwersiicht

Editeurmoonbitlang
Repositoryskills
Skill-Nummmoonbit-c-binding
Stären
35
Forks
5
Matgeliwwert Fichieren
5
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 5 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum moonbitlang op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Moonbit C Binding an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/moonbitlang/skills/tree/master/skills/moonbit-c-binding
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/moonbitlang/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/skills/moonbit-c-binding .claude/skills/moonbit-c-binding
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Moonbit C Binding an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Moonbit C Binding automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Moonbit C Binding net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

MoonBit C Binding Guide

Step-by-step workflow for binding any C library to MoonBit using native FFI.

When To Use

Use this skill when:

  • Adding extern "c" fn declarations for a C library
  • Writing C stub files (moonbit.h, MOONBIT_FFI_EXPORT)
  • Configuring moon.pkg for native builds (native-stub, link.native)
  • Choosing #borrow vs ownership transfer for FFI parameters
  • Wrapping C handles with external objects and finalizers
  • Implementing callback trampolines (closures or FuncRef)
  • Converting strings between MoonBit (UTF-16) and C (UTF-8)
  • Running AddressSanitizer to catch memory bugs in bindings

Plan Mode Instructions

If you are in plan mode and creating a plan for moonbit-c-binding work:

  1. In your final plan file, include an explicit instruction at the beginning that tells the executing agent to read the moonbit-c-binding skill before starting implementation
  2. The instruction should look like this:
    **Before starting implementation:** Use the Skill tool to load the moonbit-c-binding skill, which provides comprehensive guidance on FFI declarations, ownership annotations, C stubs, and AddressSanitizer validation.
  3. This ensures the executing agent has access to all the critical patterns and workflows documented in this skill

Type Mapping

Map C types to MoonBit types before writing any declarations.

C TypeMoonBit TypeNotes
int, int32_tInt32-bit signed
uint32_tUInt32-bit unsigned
int64_tInt6464-bit signed
uint64_tUInt6464-bit unsigned
floatFloat32-bit float
doubleDouble64-bit float
boolBoolPassed as int32_t in the C ABI (not C99 _Bool)
uint8_t, charByteSingle byte
voidUnitReturn type only
void * (opaque, GC-managed)type Handle (opaque)External object with finalizer
void * (opaque, C-managed)type Handle with #external annotationNo GC tracking; C manages lifetime
const uint8_t *, uint8_t *Bytes or FixedArray[Byte]Use #borrow if C doesn't store it
const char * (UTF-8 string)BytesNull-terminated by runtime; pass directly to C
struct * (small, no cleanup)struct Foo(Bytes)Value-as-Bytes pattern
struct * (needs cleanup)type Foo (opaque)External object with finalizer
int (enum/flags)UInt, Int, or constant enumenum Foo { A = 0; B = 1; C = 10 } maps to int32_t
callback function pointerFuncRef[...] or closureSee @references/callbacks.md
output int *Ref[Int]Borrow the Ref

Workflow

Follow these 4 phases in order.

Phase 1: Project Setup

Set up moon.mod.json and moon.pkg for native compilation.

Module configuration (moon.mod.json): Add "preferred-target": "native" so that moon build, moon test, and moon run default to the native backend:

json
{
  "preferred-target": "native"
}

Package configuration (moon.pkg):

moonbit
options(
  "native-stub": ["stub.c"],
  targets: {
    "ffi.mbt": ["native"]
  },
)

Key fields:

FieldPurpose
"native-stub"C source files to compile. Must be in the same directory as moon.pkg.
targetsGate .mbt files to backends: "ffi.mbt": ["native"]
link(native("cc-flags": ...))Compile flags (-I, -D). Only for system libraries.
link(native("cc-link-flags": ...))Linker flags (-L, -l). Only for system libraries.
link(native("stub-cc-flags": ...))Compile flags for stub files only
link(native(exports: ...))Export MoonBit functions to C (reverse direction)

Warning — supported-targets: Avoid supported-targets: ["native"]. It prevents downstream packages from building on other targets. Use targets to gate individual files instead.

Warning — cc/cc-flags portability: Setting cc disables TCC for debug builds. Setting cc-flags with -I/-L breaks Windows portability. Only set these for system libraries.

Including library sources: All files in "native-stub" must be in the same directory as moon.pkg. For inclusion strategies (flattening, header-only, system library linking), see @references/including-c-sources.md.

Phase 2: FFI Layer

Write extern declarations and C stubs together. Keep externs private; expose safe wrappers in Phase 3. Both extern "c" and extern "C" are valid — choose one casing and be consistent (e.g., match extern "js" if also targeting JS).

External object pattern (C handle with cleanup, GC-managed):

mbt
// ffi.mbt (gated to native in targets)

///|
type Parser  // opaque type backed by external object

///|
extern "c" fn ts_parser_new() -> Parser = "moonbit_ts_parser_new"

///|
#borrow(parser)
extern "c" fn ts_parser_language(parser : Parser) -> Language = "moonbit_ts_parser_language"
c
// stub.c
#include "tree_sitter/api.h"
#include <moonbit.h>

typedef struct { TSParser *parser; } MoonBitTSParser;

static void moonbit_ts_parser_destroy(void *ptr) {
  ts_parser_delete(((MoonBitTSParser *)ptr)->parser);
  // Do NOT free ptr -- GC manages the container
}

MOONBIT_FFI_EXPORT
MoonBitTSParser *moonbit_ts_parser_new(void) {
  MoonBitTSParser *p = (MoonBitTSParser *)moonbit_make_external_object(
    moonbit_ts_parser_destroy, sizeof(TSParser *)
  );
  p->parser = ts_parser_new();
  return p;
}

#external annotation pattern (C pointer, C-managed lifetime):

When C fully manages the pointer's lifetime (no GC cleanup needed), annotate the type with #external. The pointer is passed as raw void* without reference counting:

mbt
///|
#external
type RawPtr  // void*, not GC-tracked

///|
extern "c" fn raw_create() -> RawPtr = "lib_create"

///|
extern "c" fn raw_destroy(ptr : RawPtr) = "lib_destroy"

#external is an annotation (like #borrow and #owned) — it goes on its own line before the type declaration, not on the same line.

No C stub wrapper or moonbit_make_external_object is needed — the MoonBit extern calls the C function directly. Use this when the C API has explicit create/destroy functions and you want manual lifetime control.

Ownership annotations:

AnnotationWhen to use
#borrow(param)C only reads during the call, does not store a reference
#owned(param)Ownership transfers to C; C must moonbit_decref when done

Rules:

  • Annotate every non-primitive parameter as #borrow or #owned.
  • Primitives (Int, UInt, Bool, Double, etc.) are passed by value — no annotation needed.
  • If unsure whether C stores a reference, do NOT use #borrow.
  • Use Ref[T] with #borrow for output parameters where C writes a value back.

For detailed ownership semantics, see @references/ownership-and-memory.md.

String conversion across FFI:

MoonBit Bytes is null-terminated by the runtime, so it can be passed directly to C functions expecting const char *. For the reverse direction (C string to MoonBit), use moonbit_make_bytes + memcpy:

c
// C side: return a C string as MoonBit Bytes
MOONBIT_FFI_EXPORT
moonbit_bytes_t moonbit_get_name(void *handle) {
  const char *str = lib_get_name(handle);
  int32_t len = strlen(str);
  moonbit_bytes_t bytes = moonbit_make_bytes(len, 0);
  memcpy(bytes, str, len);
  return bytes;  // if str was malloc'd, free(str) before returning
}
mbt
// MoonBit side: decode UTF-8 Bytes to String
// Requires import "moonbitlang/core/encoding/utf8" in moon.pkg
///|
pub fn get_name(handle : Handle) -> String {
  @utf8.decode_lossy(get_name_ffi(handle))
}

Value-as-Bytes pattern (small struct, no cleanup):

c
MOONBIT_FFI_EXPORT
void *moonbit_settings_new(void) {
  return moonbit_make_bytes(sizeof(settings_t), 0);
}
mbt
///|
struct Settings(Bytes)  // backed by GC-managed Bytes, no finalizer

moonbit.h core API:

APIPurpose
moonbit_make_external_object(finalizer, size)GC-tracked object with cleanup finalizer
moonbit_make_bytes(len, init)GC-managed byte array (MoonBit Bytes)
moonbit_incref(ptr)Prevent GC collection of C-held object
moonbit_decref(ptr)Release C's reference (pair with incref)
Moonbit_array_length(arr)Length of GC-managed array or Bytes
MOONBIT_FFI_EXPORTRequired macro on all exported functions

For the full API, read $MOON_HOME/lib/moonbit.h (default MOON_HOME is ~/.moon).

Phase 3: MoonBit API

Build safe public wrappers over the raw externs.

Type declarations:

mbt
///|
type Parser          // opaque, backed by external object (has finalizer)

///|
struct Settings(Bytes)  // value type, backed by GC-managed Bytes

///|
struct Node(Bytes)      // small value struct

Safe constructors and methods:

mbt
///|
pub fn Parser::new() -> Parser {
  ts_parser_new()
}

///|
pub fn Parser::set_language(self : Parser, language : Language) -> Bool {
  ts_parser_set_language(self, language)
}

Error mapping:

mbt
///|
pub fn result_from_status(status : Int) -> Unit raise {
  if status < 0 {
    raise MyLibError(status)
  }
}

For callback patterns (FuncRef, closures, trampolines), see @references/callbacks.md.

Phase 4: Testing

bash
moon test --target native -v

Run with AddressSanitizer to catch memory bugs:

bash
python3 scripts/run-asan.py \
  --repo-root <project-root> \
  --pkg moon.pkg \
  --pkg main/moon.pkg

See @references/asan-validation.md for details.

Decision Table

SituationPatternKey Action
C reads pointer only during call#borrow(param)No decref in C
C takes ownership of pointer#owned(param)C must moonbit_decref
C handle needs cleanup on GCExternal object + finalizermoonbit_make_external_object
C pointer, C manages lifetime#external annotation on typeNo GC tracking; call C destroy explicitly
Small C struct, no cleanupValue-as-Bytesmoonbit_make_bytes + struct Foo(Bytes)
C returns null on failureNullable wrapperCheck null, return Option or raise error
Callback with data parameterFuncRef + Callback trickSee @references/callbacks.md
Callback without data parameterFuncRef onlySee @references/callbacks.md
C string (UTF-8) outputBytes across FFImoonbit_make_bytes + memcpy in C; @utf8.decode_lossy in MoonBit
Output parameter (int *result)Ref[T] with #borrowC writes into Ref, MoonBit reads .val

Common Pitfalls

  1. Using #borrow when C stores the pointer. The GC may collect the object while C holds a stale reference. Only borrow for call-scoped access.

  2. Forgetting moonbit_decref on owned parameters. Every non-borrowed, non-primitive parameter transfers ownership to C. Missing decrefs leak memory.

  3. Calling free() on external object containers. The GC manages the container. Finalizers must only release the inner C resource.

  4. Using moonbit_make_bytes for structs with inner pointers. Bytes have no finalizer, so inner heap allocations leak. Use external objects instead.

  5. Missing moonbit_incref before callback invocation. When C calls back into MoonBit, the GC may run. Incref MoonBit-managed objects before the call; decref afterward.

  6. Forgetting the MOONBIT_FFI_EXPORT macro. Without it, the function is invisible to the MoonBit linker.

References

@references/ownership-and-memory.md @references/callbacks.md @references/including-c-sources.md @references/asan-validation.md

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Moonbit C Binding?

Guide for writing MoonBit bindings to C libraries using native FFI. Use when adding extern "c" declarations, writing C stubs with moonbit.h, configuring native-stub and link.native in moon.pkg, choosing

Firwat Moonbit C Binding op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Moonbit C Binding besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Moonbit C Binding an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/moonbitlang/skills/tree/master/skills/moonbit-c-binding an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Moonbit C Binding benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Moonbit C Binding benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Moonbit C Binding domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Moonbit C Binding gratis?

De Skill gëtt vum moonbitlang op GitHub publizéiert. Kuckt am Repository no de Lizenzbedéngungen. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇