nim-c-wrappers
Skill4 starsChanged 3 months agoMITView on GitHub
Turn low-level C FFI bindings into an idiomatic Nim API, with safer types, cleaner module boundaries, resource management, callbacks, enums, bitflags, and exception-based error handling. Use when building a high-level Nim wrapper around a C library or improving the usability of existing raw bindings.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- planetis-m/skillsword for word, first seen Jul 16, 2026
Other versions1 project uses a version of this.
Word for word · 1
- planetis-m/skills★ 59100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository18 other files it gives its agents.
- atlas-package-clonerSkill
- buildSkill
- docs-genSkill
- format-codeSkill
- nim-api-designSkill
- nim-c-bindingsSkill
- nim-code-organizationSkill
- nim-debuggingSkill
- nim-defect-analysisSkill
- nim-doc-commentsSkill
- nim-error-handlingSkill
- nim-fuzzingSkill
- nim-mcp-toolsSkill
- nimonypluginsSkill
- nim-ownership-hooksSkill
- nim-style-guideSkill
- nim-testingSkill
- run-testsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
13 rules. About 0 are common, 6 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 12
Use a two-layer design: raw FFI layer (ABI-faithful) + ergonomic Nim layer (safe, idiomatic).
- Very specific: line 19
Use importc with cdecl (or stdcall if the library requires it).
- Very specific: line 21
Never reorder struct fields: Use object in C field order.
- Very specific: line 22
Use incompleteStruct and list only needed fields to reduce ABI risk.
- Distinctive: line 26
Keep pointer types as C intends — do not convert them in the raw layer.
- Distinctive: line 62
Do not create custom exception types unless callers handle them differently.
- Very specific: line 70
Keep raw constant names in C style (e.g., CURLE_OK).
- Very specific: line 71
When a C identifier collides with a Nim keyword, rename the Nim identifier and use importc: to map to the original C name.
- Very specific: line 80
Add static: doAssert sizeof(T) == N and offsetOf checks in tests to verify struct layouts.
- Distinctive: line 81
Test ABI with compile + link + smoke test + runtime checks.
- Very specific: line 86
Map types: Use the type table. Verify sizes with static: doAssert sizeof.
- Distinctive: line 88
Write ergonomic wrappers: Add destructors for owned resources (move-only or RC).
- Distinctive: line 90
Iterate: Add missing APIs as needed.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Nim C Wrappers
Rules
Architecture
- Use a two-layer design: raw FFI layer (ABI-faithful) + ergonomic Nim layer (safe, idiomatic). Keep the raw layer thin and stable.
- Split modules by library domain. Mirror the C header structure for large libraries.
- Centralize shared types in a
lib_raw_typesmodule to avoid cyclic imports. - Export raw symbols only for advanced users; re-export selected symbols from ergonomic modules.
Raw FFI Layer
- Use
importcwithcdecl(orstdcallif the library requires it). Prefer{.push callconv: cdecl, importc.}blocks for shared conventions. headerdeclares linker-resolved imports;dynlibloads symbols at runtime. Do not combine them on one proc. Guard library names withwhen defined(windows):etc.- Never reorder struct fields. Use
objectin C field order. Addpackedonly if C headers specify packing. - Use
incompleteStructand list only needed fields to reduce ABI risk. - For C enums, use
distinctinteger types +constvalues. Do not use Nimenumin raw bindings. Find actual enum values in C headers—do not guess. - For bitflags, use
distinctinteger types with bitwise helpers. Do not useset[Enum]. - Map C macros: numeric →
const; function-like →template; useinline procwhen arguments should evaluate once. - Keep pointer types as C intends — do not convert them in the raw layer.
Type Mapping
| C Type | Nim Type | Notes |
char | cchar | Platform-dependent signedness |
signed char | cschar | Always int8 |
unsigned char | uint8 | Safer default spelling; avoid relying on cuchar status across Nim versions |
short | cshort | Always int16 |
unsigned short | cushort | Always uint16 |
int | cint | Always int32 |
unsigned int | cuint | Always uint32 |
long | clong | ABI-sized (4 on Win64, 8 on LP64) |
unsigned long | culong | ABI-sized |
long long | clonglong | Always int64 |
unsigned long long | culonglong | Always uint64 |
size_t | csize_t | Alias for uint |
intptr_t | int | Pointer-sized signed |
uintptr_t | uint | Pointer-sized unsigned |
float | cfloat | Always float32 |
double | cdouble | Always float64 |
long double | clongdouble | Limited codegen support |
void* | pointer | Untyped |
T* | ptr T | Nullable |
T** | ptr ptr T | |
char* / const char* | cstring | NUL-terminated |
char** | cstringArray | ptr UncheckedArray[cstring] |
Struct types: object in C order. Fixed arrays: array[N, T]. Pointer+length: ptr T + csize_t. Raw buffers: ptr UncheckedArray[T]. Opaque handles: pointer or ptr OpaqueObj (empty object).
Ergonomic Layer
- In
=destroy, explicitly call=destroyon owned nested GC-managed fields (string, seq) after releasing C resources. - Define ownership hooks in the same module as the type. Cross-module hook definitions are a compile error.
- Raise exceptions (IOError, ValueError, etc.) for C errors — do not return result wrappers that only carry ok/kind/message.
- Do not create custom exception types unless callers handle them differently.
- Catch errors only at translation boundaries (C return code → Nim exception, or exception → domain result). Let exceptions propagate otherwise.
Naming
- In raw bindings, match C identifier names directly.
importcwithout an explicit string resolves the C symbol from the Nim name.- Strip redundant C prefixes (LIB_, foo_) in the ergonomic layer.
- Keep raw constant names in C style (e.g.,
CURLE_OK). - When a C identifier collides with a Nim keyword, rename the Nim identifier and use
importc:to map to the original C name.
Callbacks
- Declare callbacks as plain C-callable procs such as
proc onEvent(code: cint; userData: pointer) {.cdecl.}. - Pass closure state through
userdataviarawProc/rawEnv. Seereferences/callback_pattern.md.
Verification
- Add
static: doAssert sizeof(T) == NandoffsetOfchecks in tests to verify struct layouts. - Test ABI with compile + link + smoke test + runtime checks.
Workflow
- Read the C API. Identify structs, enums, functions, callbacks, and ownership semantics.
- Map types. Use the type table. Verify sizes with
static: doAssert sizeof. - Write raw bindings. One module per C header or subsystem. Centralize shared raw types to avoid cycles. Use
importc, correct calling convention,packedonly when C specifies it. Use typed integer aliases for enums. - Write ergonomic wrappers. Add destructors for owned resources (move-only or RC). Raise exceptions for C errors. Re-export only the intended public surface. Strip prefixes.
- Test. Compile check → link check → smoke test → ABI sizeof/offset asserts → runtime ownership tests.
- Iterate. Add missing APIs as needed. Keep raw layer stable.
Common Mistakes
| Mistake | Why it's wrong |
Passing Nim string directly to char* parameter | Type mismatch; use .cstring |
Using seq where C expects stable pointer | add() can reallocate, invalidating the pointer |
| Reordering struct fields | Breaks ABI layout, causes garbage values |
Using Nim enum for C enum values | ABI incompatibility; use typed integer aliases |
| Adding enum or constant values without inspecting headers | Find actual enum values in C headers, do not guess |
| Passing closures as C callbacks | C expects plain function pointers, not GC closures |
Storing cstring beyond the call | cstring from string.cstring dangles after the source is freed |
=dup body using result = src in RC pattern | May trigger implicit =copy instead of =dup; use field-by-field assignment |
| Wrong calling convention | Causes crashes at call sites |
References
references/move_only_resource.md— A move-only wrapper for one owner of a C handle.references/rc_resource.md— A reference-counted wrapper for shared C resource ownership.references/callback_pattern.md— C callbacks with userdata, captured Nim state, and lifetime management.references/enum_and_bitflags.md— Distinct-integer wrappers for non-contiguous enums and bitwise flags.references/module_layout.md— Separating raw FFI from an ergonomic API in two modules.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

