Expose a Nim library to C, C++ and Rust by annotating ordinary Nim procs.
You write async Nim; nim-ffi provides the whole FFI runtime — a dedicated
worker thread, a request channel, CBOR (de)serialization, an event queue and a
context/handle registry — and generates the foreign-language bindings for you.
No hand-written .h files, no manual request enums, no shared-memory plumbing.
Add nim-ffi to your library's .nimble, then import ffi:
requires "https://github.com/logos-messaging/nim-ffi >= 0.3.0"- You declare a library once with
declareLibrary(name, LibType). - You annotate procs and types with pragmas (
{.ffi.},{.ffiCtor.},{.ffiDtor.},{.ffiStatic.},{.ffiEvent.}). - You call
genBindings()last, which emits the foreign bindings.
Every request/response crosses the boundary as a single CBOR blob; the ctx
handle returned by the constructor is the only pointer that crosses. Each {.ffi.} proc runs on the library's own chronos
event loop, so bodies can await freely.
import ffi, chronos
# 1. The library's main state. The FFI context owns one instance.
type Counter = object
value: int
declareLibrary("counter", Counter)
# 2. Request/response shapes. Any {.ffi.} object or enum type becomes a
# first-class struct/class in the generated bindings and rides the CBOR wire.
type BumpRequest {.ffi.} = object
by: int
type BumpResponse {.ffi.} = object
newValue: int
# 3. Constructor: returns Future[Result[LibType, string]].
proc counterNew*(): Future[Result[Counter, string]] {.ffiCtor.} =
return ok(Counter(value: 0))
# 4. A method: first param is the library value, then any typed params.
# Return type is always Future[Result[T, string]].
proc counterBump*(
c: Counter, req: BumpRequest
): Future[Result[BumpResponse, string]] {.ffi.} =
await sleepAsync(1.milliseconds)
return ok(BumpResponse(newValue: c.value + req.by))
# 5. Destructor: exactly one param (the library value).
proc counterDestroy*(c: Counter) {.ffiDtor.} =
discard
# 6. genBindings() must be the LAST FFI call in the file (see below).
genBindings()The generated C export names are the snake_case form of the proc names, e.g.
counterBump → counter_bump.
| Pragma | Applies to | Purpose |
|---|---|---|
declareLibrary(name, LibType) |
call | Registers the library and its state type. Must run before any annotation. |
{.ffi.} on a type |
object, enum |
Registers the type for binding generation; it serializes as CBOR. |
{.ffi.} on a proc |
proc | Exposes a method. First param is the library value, then typed params; returns Future[Result[T, string]]. |
{.ffiStatic.} |
proc | Exposes a context-independent proc: no library param, and its wrapper takes no ctx — see below. |
{.ffiCtor.} |
proc | The constructor. Returns Future[Result[LibType, string]]; creates the FFI context. |
{.ffiDtor.} |
proc | The destructor. Exactly one param (x: LibType); tears the context down. Must cancel and await everything it spawned — see the teardown contract. |
{.ffiEvent[: "wire_name"].} |
proc (empty body) | A library-initiated callback. Call the proc from any {.ffi.} handler to fire it. The wire name is optional — see below. |
{.ffiReverse[("wire_name", timeout = ms)].} |
proc (no body) | Experimental. An interface that the library calls and the host implements at runtime. See below. |
{.ffiReverseEvent[: "wire_name"].} |
proc (with body) | Experimental. A host-emitted event. The body is the handler and runs on the FFI processing thread. See below. |
{.ffiHandle.} |
ref object |
Marks a type as an opaque handle: it stays server-side and crosses the wire as a uint64 id. |
{.ffiConst.} |
const |
Re-emits the value as a native constant in every generated binding — see below. |
genBindings() |
call | Emits the bindings. Must be the last FFI call in the compilation root. |
{.ffi.} on an enum gives each language its own native enum:
type Level {.ffi.} = enum
lLow = "low"
lHigh = "high"typedef enum { LEVEL_L_LOW = 0, LEVEL_L_HIGH = 1 } Level; /* C */
enum class Level { lLow = 0, lHigh = 1 }; // C++
pub enum Level { #[serde(rename = "low")] LLow, ... } // RustAn enum crosses the wire as text, not as its ordinal — whatever $value
yields, so the associated string if the enum declares one ("low" above) and
the symbol name otherwise (lLow). That is what cbor_serialization writes on
the Nim side, and the generated codecs map name ↔ value on the far side, so
reordering or renumbering values doesn't break an already-deployed peer.
Explicit ordinals are carried into the foreign enum so the two sides agree if
you ever cast.
{.ffiConst.} copies a Nim const into the generated bindings, so callers
don't hand-maintain a second copy of a limit, a default or a protocol string:
const
MaxPeers* {.ffiConst.} = 42
DefaultTimeoutMs* {.ffiConst.}: uint32 = 3 * 1000
Greeting* {.ffiConst.} = "hello"static const int64_t MAX_PEERS = 42LL; /* C */
static const uint32_t DEFAULT_TIMEOUT_MS = 3000;
static const char* const GREETING = "hello";constexpr int64_t MAX_PEERS = 42LL; // C++pub const MAX_PEERS: i64 = 42; // RustInteger, float, bool and string consts are supported; anything else is a
compile error. The value is whatever the const evaluates to, so computed
expressions arrive folded. Names are re-cased to UPPER_SNAKE, preserving
acronyms (httpTTL → HTTP_TTL). A constant is a compile-time value in each
language, not a symbol exported by the shared library — it never crosses the
wire.
A ## doc comment on an annotated proc is carried through to every generated
binding, so the exported API is documented once, at the source:
proc myTimerEcho*(
timer: MyTimer, req: EchoRequest
): Future[Result[EchoResponse, string]] {.ffi.} =
## Sleeps `delayMs` then echoes the message back.
...becomes /** Sleeps `delayMs` then echoes the message back. */ above both the
exported symbol and the <lib>_ctx_echo wrapper in the C header, /// ... on
the C++ class method and the Rust pub fn, and a ; comment in the CDDL
schema. Multi-line doc comments are preserved as-is.
Only ## doc comments are propagated, and only on procs — a plain # comment
above the proc, and any comment on a {.ffi.} type or its fields, is dropped by
Nim's parser before the macro can see it.
Every {.ffi.} / {.ffiCtor.} proc must have an explicit
Future[Result[T, string]] return type — even for synchronous logic (just
return ok(...) without awaiting). The Result's error string is delivered to
the foreign caller as the failure message.
A {.ffi.} proc is a method: it takes the library value, and its wrapper takes a
ctx, so the host must construct the library to call it. A stateless utility
shouldn't have to pay for that. Annotate it {.ffiStatic.} instead — drop the
library param, and the ctx disappears from the generated wrapper:
proc counterParse*(text: string): Future[Result[BumpRequest, string]] {.ffiStatic.} =
return ok(BumpRequest(by: text.parseInt()))/* {.ffi.} method */ counter_ctx_bump(ctx, &req, on_reply, ud);
/* {.ffiStatic.} — no ctx */ counter_static_parse(text, on_reply, ud);The wrapper is <lib>_static_<proc>, not <lib>_<proc>, for the same reason a
method's is <lib>_ctx_<proc>: <lib>_<proc> is the raw symbol the dylib
exports. In C++ and Rust a static is an associated function on the ctx type
(EchoCtx::lib_version()), taking the timeout a method reads from its ctx.
The handler still needs an FFI thread, so it runs on the library's static
context: created on the first {.ffiStatic.} call, then alive for the rest of
the process — no ctx owns it, so nothing tears its thread pair down, and it holds
one of the pool's slots. It has no myLib, which is why a static proc cannot
take the library value.
There is no foreign teardown for it. From Nim, destroyStaticFFIContext(pool)
stops the thread pair and frees the slot; it is only sound once nothing will call
a {.ffiStatic.} proc again, so it is meant for process shutdown and tests.
The macro rejects an {.ffiHandle.} parameter or return: a handle is registered
in the context that created it, which a static proc cannot reach.
A {.ffiDtor.} must cancel and await everything it spawned. The pool recycles
a context by handing its slot — including the live FFI and event thread pair and
their chronos dispatcher — to the next owner, and the only proof that the previous
owner is gone from that thread is its teardown having run to the end. The runtime
cannot make up for a teardown that gave up: chronos exposes no way to enumerate,
let alone cancel, the futures of a thread outside a debug build, and a cancel is
cooperative in any case.
A teardown that overruns -d:ffiTeardownTimeoutMs (10 s) is cancelled at the
timeout; one that raises stops there. Either way the runtime treats the context as
unsafe to reuse and quarantines it:
| Teardown completed | Teardown cut short or raised | |
|---|---|---|
<lib>_ctx_destroy |
RET_OK |
RET_ERR |
| The library object | freed | kept alive — orphaned work may still hold pointers into it |
| The pool slot | back in the pool | claimed for the life of the process |
| In-flight callbacks | done before the destroy returned | can still fire, so keep their userData alive |
Quarantine costs one of the 32 slots permanently, so a library that habitually
overruns its teardown will exhaust the pool. FFIContextPool.quarantinedSlots()
reports the count from Nim, every quarantine is logged at error, and so is the
pool-exhausted error once any slot has been quarantined.
A callback must not destroy its own context: a result callback runs on the FFI
thread and a listener on the event thread, and the recycle waits for both.
<lib>_ctx_destroy from such a callback returns RET_ERR at once and leaves the
context live, so destroy it later from a host thread. A callback may destroy a
different context.
<lib>_ctx_destroy recycles: the slot's FFI and event thread pair stays up for
the next owner. Once no context is live the pool joins that pair, so a host that
destroys what it created leaves no thread of the library running. A finalize
under a live thread crashes the process, which is what this avoids.
Two cases keep a pair alive anyway: a host that exits still owning a context, and
a {.ffiStatic.} call, whose shared context holds its slot for the life of the
process. <lib>_shutdown() stops both, from atexit or the last line of main.
It returns 0 when every context stopped, 1 when one was left running. A context
you had not destroyed still runs its {.ffiDtor.} on the way out, so do not
repeat that cleanup yourself. Its slot is quarantined all the same, because
nothing freed the library object: later calls on that handle fail, and the slot
is gone from the pool's 32.
Each request carries a result callback. It receives one of these status codes
(ret / err_code):
| Code | Value | Terminal? | Meaning |
|---|---|---|---|
RET_OK |
0 | yes | Success; the payload carries the encoded result. |
RET_ERR |
1 | yes | Failure; the payload carries the UTF-8 error string. |
RET_MISSING_CALLBACK |
2 | — | No callback was passed; the request path reports this itself. |
RET_STALE_WARN |
3 | no | Progress ping — the handler is still running. |
nim-ffi never times a handler out. A slow request runs to its natural
RET_OK / RET_ERR; it is never cancelled (a hard-cancel mid-call into the
underlying library can leave it half-applied). Instead, while a handler is still
in flight the callback receives a non-terminal RET_STALE_WARN every 5s
(Android's ANR interval; override at build time with
-d:ffiStaleWarnIntervalMs=<ms>), with the payload carrying the elapsed
milliseconds as a decimal string. The dev decides what to do with a slow request
— keep waiting, surface a spinner, tear the context down — nim-ffi does not
decide for them.
RET_STALE_WARN may fire any number of times and is always followed by
exactly one terminal RET_OK / RET_ERR. A caller that only wants the final
answer must ignore it (do not treat a non-zero code as an error without checking
for RET_STALE_WARN first). The generated higher-level typed wrappers currently
ignore it; the progress signal is delivered at the raw result-callback boundary.
An event is a proc with an empty body annotated {.ffiEvent.}. You fire it by
calling it with a typed payload from inside any {.ffi.} handler; the foreign
side receives it through a registered callback.
type PeerConnected {.ffi.} = object
id: string
proc onPeerConnected*(peer: PeerConnected) {.ffiEvent.} # wire name: "on_peer_connected"
proc counterBump*(c: Counter, req: BumpRequest): Future[Result[BumpResponse, string]] {.ffi.} =
onPeerConnected(PeerConnected(id: "p-1"))
return ok(BumpResponse(newValue: c.value + req.by))The wire name is optional: when omitted it is derived from the proc name
(onPeerConnected → on_peer_connected), matching how {.ffi.} derives its C
export symbol. Pass a string literal ({.ffiEvent: "custom_name".}) only when
you need a name that differs from the proc.
Reverse FFI lets the library declare an interface that the host implements at runtime. Both pragmas use CBOR.
# Host-implemented interface: no body, returns Future[Result[T, string]].
# A comment-only body keeps the doc: Nim drops a `##` after a declaration without `=`.
proc fetchHostClock(
precision: string
): Future[Result[HostClock, string]] {.ffiReverse.} =
## Asks the host for its wall clock.
# Host-emitted event: the body runs on the FFI processing thread.
proc onHostTick(tickNo: int) {.ffiReverseEvent.} =
lastHostTick = tickNoAn {.ffi.} handler awaits fetchHostClock(...) like any async proc. The host
implementation runs on a per-context reverse worker thread, never on the FFI
thread, so it may block without stalling it. The host answers through
<lib>_reverse_reply, now or later and from any thread. Workers start on the
first set_impl; -d:ffiReverseWorkers sets the count (default 1), so by
default one blocked implementation holds every other reverse call of its context
until it returns or their deadlines fire.
typedef void (*FFIReverseImpl)(void* ctx, uint64_t call_id, const uint8_t* args,
size_t args_len, void* user_data);
typedef void (*FFIReverseRelease)(void* user_data);
int <lib>_set_<wire>_impl(void* ctx, FFIReverseImpl impl, void* user_data,
FFIReverseRelease release); /* impl == NULL unregisters */
int <lib>_reverse_reply(void* ctx, uint64_t call_id, int ret_code,
const uint8_t* reply_cbor, size_t reply_len);
int <lib>_emit_<wire>(void* ctx, const uint8_t* payload_cbor, size_t payload_len);set_impl never waits. With a release the library owns user_data and frees
it after the replaced implementation's last running invocation, so replacing an
implementation is safe from any thread, even from inside itself. With a NULL
release the host keeps user_data valid until the context is destroyed. If
set_impl fails, the caller keeps user_data. Status codes are the shared
NIMFFI_RET_*.
The C header adds typed helpers: <lib>_ctx_set_<wire>_impl,
<lib>_decode_<wire>_args, <lib>_reverse_reply_<wire>,
<lib>_reverse_reply_err and <lib>_ctx_emit_<wire>. The reply helpers take
the ctx token the implementation is handed, so a reply deferred past the
context's destroy fails with NIMFFI_RET_INVALID_CTX instead of reading a
freed <Ctx> wrapper. The <lib>_ctx_reverse_reply_* variants take the
wrapper and are safe only while it is alive. The helpers that encode, the
typed reply and <lib>_ctx_emit_<wire>, take a trailing char** err: when the
value does not encode they return NIMFFI_RET_ERR and, unless err is NULL,
set *err to the reason, which the caller frees. A reply that does not encode
still answers the call, with that reason as the error.
The C++ and Rust bindings pass a release, so the library owns their
closures, and turn a C++ exception or a Rust panic in the implementation into a
failed call.
The implementation gets a copyable call token with reply and fail. C++
receives the arguments by const&, borrowed until the implementation returns,
so a deferred reply captures a copy; Rust closures own theirs and move them.
reply, fail, set<X>Impl / set_<x>_impl, clear… and emit… return
Result<void> in C++ and Result<(), String> in Rust. The error reads
"<op> <wire>: <reason>", where the reason is the encoder's message or the
NIMFFI_RET_* name of the refusal, for example
"reply fetch_host_clock: NIMFFI_RET_INVALID_CTX" for a reply after destroy.
A reply that does not encode still answers the call, with the reason as the
error. The C++ token's failRaw stays a noexcept bool, for a catch block.
ctx->setFetchHostClockImpl([](MyTimerCtx::FetchHostClockCall call, const std::string& precision) {
// `precision` is borrowed until this returns: capture a copy, never a reference.
std::thread([call, precision] { call.reply(HostClock{now_ms(precision), "CET"}); }).detach();
});
auto r = ctx->host_clock(); // Nim awaits the C++ impl
ctx->emitOnHostTick(7); // reverse event, fire-and-forgetctx.set_fetch_host_clock_impl(|call, precision: String| {
// `precision` is owned: move it into the thread.
std::thread::spawn(move || { call.reply(&HostClock { unix_ms: now_ms(&precision), zone: "CET".into() }); });
});
let r = ctx.host_clock()?; // Nim awaits the Rust impl
ctx.emit_on_host_tick(7); // reverse event, fire-and-forget| Situation | Behavior |
|---|---|
| No implementation registered | The call fails at once. |
| No reply before the deadline | The call fails after ReverseCallTimeoutMs (10 s) or the timeout = ms of the proc, and reverse_call_timeout fires with reason: "timeout". |
Deadline or cancelSoon() while the call is queued |
The worker skips the call, and the implementation never runs. |
| Deadline or cancel while the implementation runs | The call fails at once, and the late reply is dropped by call id. |
| Two replies for one call id | The first one completes the call; the second is dropped. |
args after the implementation returns |
No longer valid: a deferred reply copies what it needs. |
More than -d:ffiReverseQueueDepth (1024) calls wait for a worker |
The next one fails at once, and reverse_call_timeout fires with reason: "queue_full". |
A reply over -d:ffiMaxRequestPayloadBytes (when set), or NULL with a length |
NIMFFI_RET_TOO_LARGE or NIMFFI_RET_INVALID_ARGUMENT; nothing is queued. |
| Recycle or shutdown has begun | A new reverse call fails at once instead of parking. |
| The C++ implementation throws, or the Rust one panics | The call fails with the message; the process keeps running. |
A worker inside one implementation past ReverseCallTimeoutMs |
reverse_worker_blocked fires with the proc and the time spent in it, then reverse_worker_recovered when it returns. |
| Recycle while an implementation runs | Waits RecycleTimeout, then quarantines the slot with RecycleFailure.ReverseImplBlocked. |
Destroy, park or <lib>_shutdown with a stuck worker |
The stuck worker leaks with the slot, and so does its user_data: release never runs under it. |
| A host implementation destroys its own context | <lib>_destroy fails at once with RET_ERR, and the context stays usable: destroy it from another thread. |
A host implementation calls <lib>_shutdown |
The call returns; the worker that runs it leaks and is not joined. |
{.ffiReverseEvent.} emit |
The return code reports the enqueue only. |
A reverse call takes no {.ffiHandle.} parameter, and only code on the FFI
processing thread can await it: an {.ffi.} handler, or any async work running
on that thread's event loop.
To check an interface before its first call, ask which wires the host has not implemented yet. An unknown wire name is a compile error.
The check is meaningful only in a request the host sends after it has
registered its implementations: <lib>_set_<wire>_impl takes the token the
{.ffiCtor.} returns, so the host can register only once the ctor has
returned, and nothing orders that against the ctor body on the FFI thread. A
check inside the ctor races the registration and usually sees every wire
missing. Put it in a later request instead; liblogosdelivery runs it when the
host calls start_node.
Both return a Result: off the FFI processing thread there is no context to
ask, and that is an error rather than "not implemented".
let missing = ?ffiReverseMissing(["fetch_host_clock", "host_note"])
if missing.len > 0:
return err("host has not implemented " & missing.join(", "))
doAssert ffiReverseImplemented("fetch_host_clock").get()Built with -d:ffiPollMode, the same source exports the poll ABI instead: no
callbacks, every export answers with a message read from <lib>_poll(), and
the generated <lib>.h declares that shape (the message, the exports, the
codecs) for a host that brings its own loop.
- Events emitted with
dispatchFFIEvent(name): <string>arrive as the bytes given,dispatchFFIEventCborones as CBOR. A host matches on the message'sname_id. {.ffiReverse.}is the library asking the host a question and awaiting the answer; it exists only under the poll mode. The host has-d:ffiReverseCallTimeoutMs(10 s unless set) to answer.- A synchronous export (no parameters, a plain return type) stays a plain C function in both modes.
genBindings() reads the compile-time registries that the pragmas populate as
the compiler expands them, so it must come after every annotation. Since
Nim resolves imports before running the importing module's body, a multi-file
library keeps its annotations in imported sub-modules and calls genBindings()
once at the bottom of the top-level root file.
An annotation that expands after genBindings() is now a compile error
(previously it was silently dropped from the bindings). Under --ic:on, a
binding build (-d:ffiGenBindings) that calls genBindings() outside the root
module is also a compile error.
Under --ic:on, a warm cache skips sem, so a rebuild with no source change does
not run genBindings(). After you delete or edit the bindings dir, or change
-d:targetLang or -d:ffiOutputDir, delete the nimcache dir before the rebuild.
nim-ffi does not cap request payloads by default: the caller's buffer already
lives in the host's memory. A host that forwards untrusted bytes must bound
them, either before the FFI boundary or build-wide with
-d:ffiMaxRequestPayloadBytes=<n> (0 = unlimited). Like the abi = c
trusted-caller assumption, this is the host's call.
A nim-ffi library ships from two separate compiles of the same source,
because binding emission is gated behind -d:ffiGenBindings: without that
define genBindings() is a no-op, so the normal build just produces the shared
library and nothing else.
1. Build the shared library (the artifact your host loads):
nim c --app:lib --noMain --nimMainPrefix:libmylib mylib.nim2. Emit the foreign bindings — add the binding defines and --compileOnly,
which stops after codegen: the binding files are written during macro expansion,
so there's no library to link (no --app:lib/-o:/dev/null needed). The
generated files (for targetLang=c: the <name>.h header your host includes,
plus a CMakeLists.txt) land in -d:ffiOutputDir:
nim c -d:ffiGenBindings -d:targetLang=rust,cpp,c --compileOnly mylib.nim-d:targetLang— which generator(s) run; pass a comma-separated list to emit several from one compile:- Language bindings:
rust(default),cpp,c. All three speak CBOR. cddl— a CDDL schema of the CBOR wire, not a language binding at all.
- Language bindings:
-d:ffiOutputDir— override where the generated files land. Defaults to<lang>_bindings/next to the compiled source.-d:ffiSrcPath— override the Nim source path embedded in the generated build files. Defaults to the compiled source made relative to the output dir.
--app:lib builds a shared library; --noMain hands program entry to the
foreign host rather than Nim's own main. To initialize the Nim runtime,
declareLibrary("<name>", …) emits an initializeLibrary() export that calls
lib<name>NimMain() — the symbol Nim's NimMain is renamed to by
--nimMainPrefix. So the prefix must be exactly lib + the declareLibrary
name, on both compiles above, or the library fails to link. For
declareLibrary("my_timer", …) that is --nimMainPrefix:libmy_timer.
Library-naming collisions. When several nim-ffi libraries are loaded into
one process (as the C++ end-to-end test does with timer + echo), each must
use a distinct library name — and therefore a distinct --nimMainPrefix —
so their exported NimMain, initializeLibrary and per-symbol names don't
clash. The example libraries deliberately differ: libmy_timer vs libecho.
-
examples/timer— a self-contained Nimble project covering the ctor, sync and async methods, multi-param methods, events, and C / C++ / Rust / CDDL bindings with runnable clients. Start here:cd examples/timer && nimble install -y ../.. && nimble build
-
examples/echo— a second minimal library, loaded alongsidetimerin the C++ end-to-end test to prove two libraries coexist in one process.