Foundations

A stable C ABI

A program compiled today should keep working with the library built next year, and a Python script should call a library written in C++. Both need a stable ABI: a binary interface whose rules do not change. C++ does not give one; C does. This page explains why, and the small set of rules a C facade over a C++ library follows. The last part shows RASM's.

In short

  • The API is what the source code sees; the ABI is what the machine code sees: symbol names, the layout of every struct, how arguments travel, who frees what.
  • C++ types (std::string, classes, exceptions, templates) have layouts and names that differ between compilers and versions. C has one plain layout per platform, which every language can call.
  • A C facade hides objects behind opaque pointers and names them by integer handles; it uses only fixed-size types.
  • A struct that may grow starts with its size, so an old program and a new library agree on what each one knows.
  • No exception crosses the line: errors become codes and a per-thread last error.
  • Memory stays with whoever made it: inputs are borrowed for the call, outputs go into the caller's buffers.
  • A callback is a C function pointer and a user_data; what the library hands it lives only during the call, on the caller's thread, and it must return normally.
  • A version number and the rule "only add at the end" keep old binaries working.

1The problem: C++ has no stable ABI

A C++ library compiled into a shared library exposes its machine-level interface. Four parts of it change from one compiler, standard library or library version to the next.

void load(std::string) _Z4loadNSt7... ?load@@YAXV... clang/gcc vs MSVC

Mangled names

C++ encodes the parameter types into the symbol name, and each compiler family encodes them its own way. A C function is just its name.

std::string, MSVC STL: 32 B buffer / ptr size cap libc++: 24 B, another order cap size ptr

Standard library layouts

A std::string or std::vector passed across the line must have the same layout on both sides. It does not between MSVC's STL, libc++ and libstdc++, or between debug and release.

library: throw Python / C frame no handler: the process ends

Exceptions

An exception unwinds through the caller's stack frames. A C, Python or Rust caller has no handler for it, and unwinding through foreign frames is undefined.

v1 class, as the program knows it a, b v2 class, as the library uses it a, b c: past the end

Class layouts and vtables

A new member, a new virtual function or an inline method changes sizes and offsets that the caller compiled in. The program and the library then disagree about memory.

Rebuilding everything with one compiler hides these problems for a C++ program that links a static library. It does not help a Python script, a C# game or a program shipped last year.

2C as the common language

Every platform has one C calling convention and one C struct layout, written down in its ABI document. Every language can call it: Python's ctypes, C#'s P/Invoke, Rust's extern "C", Zig, Go, Java's FFM. So the library keeps its C++ inside, and offers a facade: a header of plain C functions and structs, compiled with extern "C", so each function's symbol is just its name.

C Python ctypes C# P/Invoke Rust, Zig the ABI line: plain C only C layer check, convert, catch handles ⇄ objects C++ engine classes, std::, templates
Only C types cross the dashed line. The C++ engine behind it can change as it likes, as long as the C layer keeps the line the same.

The facade is thin: each C function checks its arguments, converts them to C++ types, calls one C++ function and converts the result back. It adds no engine features, so it stays easy to keep in step with the C++ API.

3Objects: opaque pointers and integer handles

The caller must hold the library's objects without knowing their layout. There are two ways, and a facade often uses both.

Opaque pointer

engine* e library only struct engine; declared, never defined

For a few big, long-lived objects with create and destroy calls. The layout can change freely.

Integer handle

generation index 63310 id = generation << 32 | index 0: no object (generations start at 1)

For the many small objects: meshes, lights, entities. A plain 64-bit number, so any language can store, compare and hash it.

A handle is a generational handle packed into one integer. The generation must fit in its bits, so the table must stop reusing a slot before its generation passes 32 bits: retiring the slot costs one slot in four billion reuses. Wrapped in a one-field struct per object type, { uint64_t id; }, the handle is still 8 bytes in a register, but C stops you from passing a light where a mesh is wanted.

4Only fixed-size types

typedef uint32_t format; enum { FORMAT_RGBA8 = 1 }; 4 bytes

Enums

A C enum may be 1, 2 or 4 bytes. A uint32_t with constants has one size, and each constant a fixed value.

1C bool 4 bytesuint32_t bool like VkBool32

Booleans

C99 bool is one byte, but C# marshals a bool as four. A uint32_t is the same everywhere.

p h e l l o \0 p n n items

Strings and arrays

A UTF-8 const char* instead of a string class; a pointer and a count instead of a vector.

Structs hold only fixed-size fields and pointers, so their layout is the platform's C layout. A binding copies the fields in order (Python's ctypes.Structure, C#'s [StructLayout(Sequential)], Rust's #[repr(C)]) and gets the same bytes. The calling convention is fixed too: on 32-bit Windows a macro spells out __cdecl; everywhere else there is only one C convention.

5Structs that grow

A config struct gets new fields over the years. If the library simply used its new, bigger struct, an old program's smaller one would be read past its end. The fix, used by Win32 (cbSize) and Vulkan (sType), is a size field: the caller sets it to sizeof the struct its header knows.

old program (1.0) → new library (1.1) size=12 a b size a b c = default the library reads 12 bytes; c was not in 1.0 new program (1.1) → old library (1.0) 16 a b c the library has no c so creation refuses: a newer minor version A get call writes only the caller's size; an update keeps the fields past it.
An old program with a new library works: what it does not know takes the default. A new program with an old library would set options the library ignores, so the library refuses it at the version check (section 8).

Three kinds of call read the size differently:

An init function fills a struct with the library's defaults and sets the size: one call, and a binding gets the same defaults as C. In an array of sized structs, every element must have the first one's size, because the library steps through the array by it. Small value structs (a vector, a matrix) never grow: changing one would mean a new struct and new functions.

Pick the header the program was built with, the library it runs with, and the kind of call. Find the pair the library must refuse.

6Errors without exceptions

  1. Check every pointer, size and enum value at the line: a bad argument is a code, never a crash.
  2. Call the C++ code inside try.
  3. Catch every exception: out of memory becomes its own code, anything else an internal error.
  4. Record the message as the thread's last error, and return the code.

A function returns an integer code (0 for success, negative for an error), or a 0 handle when it creates something. The message goes into a last error string kept per thread, like errno: two threads never overwrite each other's message. A logging callback lets a binding route the library's log into its own; it may run on any thread the library logs from, so it must be thread-safe. The library must not hold a lock while it runs: a callback that calls the library back would wait for itself.

7Who owns which memory

Two sides with two allocators must never free each other's memory: a C runtime's free on memory from another runtime's malloc corrupts both heaps. So each side frees only what it allocated.

caller library read during the call

In: borrowed

Strings, arrays and structs are read during the call only. The library copies what it keeps.

caller'sbuffer library writes up to capacity

Out: the caller's buffer

The snprintf rule: write what fits, return the full length. Call once with no buffer to learn the size.

object createdestroy pointers into it: until refilled

Library objects

Big results (an image) live in an object with create and destroy calls. It can be refilled, so a per-frame result allocates nothing.

8Callbacks: the library calls you

Some work happens inside the library, at a time only the library knows: a render pass records its commands while the library builds the frame. The caller gives a callback: a plain C function pointer and a void* user_data, which the library passes back on every call. Each language can make such a pointer: Python's ctypes.CFUNCTYPE, C#'s Marshal.GetFunctionPointerForDelegate or [UnmanagedCallersOnly], Rust's extern "C" fn.

time → your code library command handle your loop execute(graph) records the frame pass Acallback(ud, cmd) pass Bcallback(ud, cmd) your loop valid valid refused refused refused
One call of execute: the library calls back into your code once per pass, on your thread, and the command handle it gives is live only inside that call. A kept handle used later is refused, not a crash.

A callback crosses the line in the other direction, so the same rules hold the other way round, and a few more:

RuleWhy
The callback returns normally: no C++ exception, no longjmp, no Rust panic leaves it.The library's own frames sit between the caller's: unwinding through them skips its cleanup. Rust's catch_unwind and Python's ctypes (which prints the exception and returns) stop it at the line.
Handles given to the callback live only during the call.A command list belongs to the frame being recorded. The library marks it live before the call and dead after, so a stale handle is a refused call.
The callback runs on the thread that made the outer call, inside it.No hidden threads: a binding with a global lock (Python's GIL) already holds it.
Calls that would start a frame, change what is being recorded or free the library are refused inside a callback.Re-entrancy: the library is in the middle of a call. A flag set around the outer call turns such a call into an error code.
The function pointer and user_data stay valid as long as the library may call them.A garbage collector frees a delegate or a CFUNCTYPE object nobody references: keep it beside the object that holds the callback.
The callback's own calls report errors like any call.The outer call can then report that something failed while it ran.

9One library, one set of names

A shared library for bindings is usually built from static libraries, so it holds the whole C++ engine and every dependency. Only the C functions should leave it: everything else is hidden. Windows exports only what is marked __declspec(dllexport); on macOS a linker list (-exported_symbol,_mylib_*) and on Linux --exclude-libs,ALL with hidden visibility do the same. Hidden symbols cannot clash with another copy of the same third-party library in the host process.

The library must also find its own files. A relative path resolved against the executable points beside python.exe under Python. So the library resolves relative paths against its own folder (the module that holds the code: GetModuleHandleExW with an address on Windows, dladdr on POSIX), and its data, such as shaders, is installed beside it.

10Versions

Within one major version, only add at the end
  • New functions: yes. Changing a function's parameters: no, add a new function.
  • New enum constants: yes, with new values. Renumbering: no.
  • New struct fields: only after the last one, in a struct with a size field.
  • Removing or reordering anything: only in a new major version.

The header carries its version as major << 16 | minor, and the library reports its own. The creation call takes the caller's version and refuses a different major version, or a newer minor one: that program may call functions or set fields this library does not have. An old minor version is fine; that is what the size fields are for.

11Pitfalls

A binding crashes in a call that works from C
Its struct does not match the header: a missing field, a 1-byte bool, a wrong order. Copy every field in order, and test the binding in CI.
An old program resets a new setting to zero
An update wrote the whole new struct from the old program's smaller one. Read only the caller's size, and keep the rest.
The process aborts with "terminate called"
An exception left a C function. Wrap every entry point in a try that catches everything.
A heap corruption on free
One side freed the other side's memory. Pair every create with the library's destroy.
The library finds no data files under Python
Relative paths resolved against the executable. Resolve them against the library's own folder.
A callback crashes after a while, from Python or C#
The garbage collector freed the callback object, and the library called a dangling pointer. Keep the object as long as the library holds the function.
A command recorded later lands in the wrong frame
A handle the callback got was kept and used after the call. Use what a callback gets only inside it.
Two copies of a library in one process mix their functions
Both export the same names. Link one, and export only your own prefix.

12In RASM

RASM's facade is include/rasm/rasm_c.h, one header over two shared libraries: rasm_c (the renderer, the Engine and the AssetLoader) and rasm_c_renderer (the renderer alone). The C layer is src/c/; the reference is the C API page.

rasm_create_light(r, &desc) your program src/c/cScene.cpp readSized: desc, up to desc->size checkEnum: desc->type try { createLight(...) } toC: LightHandle → id catch (...) → RASM_ERROR_* Renderer::createLight the C++ API spdlog sink: errors → thread's last error rasm_light { id } 0 on failure Every entry point is a function try block, so no exception crosses into your program.
Every C function has this shape: check, convert, call one C++ function inside try, convert back. RASM's own error lines reach rasm_get_last_error through a log sink, so a call whose C++ function returns nothing still reports a refusal as RASM_ERROR_FAILED.

Where RASM follows the page, and where it differs

PartThis pageRASM
Big objectsopaque pointersrasm_renderer, rasm_engine, rasm_asset_loader, rasm_image. An engine's renderer and loader belong to it.
Small objectsinteger handles{ uint64_t id; } per type, generation << 32 | index of the C++ Handle. HandlePool retires a slot at MAX_HANDLE_GENERATION (232 − 1), so every handle packs with no loss, and a valid one is never 0.
Enums and booleansuint32_tThe same. A static_assert in src/c/cApi.cpp ties every C constant to its C++ enum value, so a reordered C++ enum fails the build.
Growing structsa size field and init functionsThe same: rasm_renderer_config, rasm_engine_config, rasm_asset_loader_config, rasm_light_desc, rasm_material_desc, rasm_texture_desc, rasm_scene_environment, rasm_camera_projection; in 1.1 also rasm_view, rasm_input_event, rasm_camera_input, rasm_camera_controller, rasm_window_desc, rasm_window_info, rasm_render_target_desc, rasm_animation_play and the stats. The sizes of the version that added a struct are the smallest a caller may pass.
Errorscodes and a per-thread last errorrasm_result, rasm_get_last_error, and rasm_set_log_callback. RASM's spdlog::error lines feed the last error too.
Versionsrefuse another major, or a newer minorThe same, in rasm_renderer_create and rasm_engine_create: RASM_ERROR_VERSION. 1.1 appended windows, input, views, render targets, camera helpers, animation and stats to 1.0. 1.2 appended positions in doubles: new small structs (rasm_dvec3, rasm_transform_d) with new functions beside the float ones, since a small struct never grows, and fields at the end of the sized structs (position_d, track_ball_center_d) that add to the float field, so a 1.1 program, whose size stops before them, gets the float position plus 0. 1.3 appended tile streaming: an opaque rasm_tile_streamer, a handle rasm_tile, new sized structs, and max_bindless_textures at the end of rasm_renderer_config, so an older program's renderer gets the default. 1.4 appended terrain tiles: a new sized struct rasm_terrain_tile_desc, two small ones, two formats and a material type at the ends of their enums, and terrain at the end of rasm_material_desc, so an older program's material update keeps the material's terrain. 1.5 appended meshes built on any thread and vector features: two opaque objects (rasm_mesh_build, rasm_vector_geometry), three sized structs, a material type and vector at the end of rasm_material_desc. 1.6 appended fonts and labels: an opaque rasm_font_atlas, a handle rasm_font, two sized structs (rasm_label_desc read as an array that steps by the first element's size), a format, and font at the end of rasm_material_desc, after vector, so an older program's material update keeps the material's font. 1.7 appended picking: a handle rasm_pick, two sized structs (rasm_pick_hit written as an array that steps by the first element's size, so a newer library fills only the fields an older program knows) and a format. 1.8 appended orthographic controls and reference grids: two sized structs (rasm_camera_buttons, rasm_grid), an enum, and pan_start, pan_end and pointer at the end of rasm_camera_input, so a 1.7 program's input has no pan and zooms at the view's centre. rasm_camera_controller gained track_ball_style and track_ball_up, and rasm_input_event dx and dy, at their ends. Three behaviours changed with it: a trackball orbits as a turntable by default, its wheel scales the radius by 0.9 a step instead of subtracting it, and the default button map pans with the right and middle buttons and Shift + left, where every button orbited before; rasm_set_camera_buttons with every button RASM_CAMERA_DRAG_ORBIT brings the old drag back. 1.17 appended the render graph: opaque rasm_render_graph and rasm_commands, handles rasm_buffer, rasm_pipeline and rasm_shadow, a callback type, six sized structs, and seven fields at the end of rasm_render_target_desc (swapchain_scale to cube), so a 1.16 program's target keeps one color, no depth and one sample. 1.18 appended shadow_count and a shadows pointer at the end of rasm_view, so a 1.17 view has no shadows, and the debug and inspection calls with one sized struct, rasm_inspection, whose target string the call copies. 1.19 appended the UI: a second callback type and the calls a binding's own Dear ImGui needs to share RASM's context, with a run-time check of its struct sizes (Two copies of one library).
Callbacksa function pointer, user_data, handles live during the callrasm_pass_callback of a pass of a rasm_render_graph (1.17), called from rasm_render_graph_execute on its thread. Its rasm_commands is one object per graph, made with it, marked active only during the call: a rasm_cmd_ call outside it, or one that does not fit the pass, returns RASM_ERROR_INVALID_ARGUMENT. While a graph records, rasm_render, rasm_render_views, graph changes, resizing or destroying a render target, destroying a buffer or a texture, windows and destroying the renderer are refused (checkNotRecording). A refused call inside a callback makes execute return RASM_ERROR_FAILED. Destroying the renderer detaches its graphs: their calls fail, and rasm_render_graph_destroy still frees them. rasm_ui_callback (1.19), set with rasm_set_ui_callback, runs each frame between Dear ImGui's NewFrame and Render under the same rules: a Recording guard around it makes checkNotRecording refuse the same calls, and rasm_set_ui_callback itself.
Arrays of sized structsstep by the first element's sizerasm_render_views does, and refuses an element of another size. Input events go the other way one at a time, by index, so the library never writes past an array of a size it does not know.
Exportsonly the C namesOnly rasm_*; tools/check_install.py checks the export tables in CI.
Data filesbeside the libraryRelative paths resolve against the folder of the binary that holds RASM: the executable for a static C++ program, the shared library for the C API (setBaseModule in src/platform/paths.cpp). The install puts shaders/ beside the libraries.

Where it lives in code

WhatWhere
The headerinclude/rasm/rasm_c.h
Checks, conversions, the log sink, the version checksrc/c/cApi.h, src/c/cApi.cpp
Renderer, frame, readback, imagessrc/c/cRenderer.cpp
Scenes, entities, meshes, materials, textures, lights, camerassrc/c/cScene.cpp
Windows, input events, camera controllers, rigs and input statessrc/c/cInput.cpp
Views and render targetssrc/c/cViews.cpp
The render graph, pass callbacks and commandssrc/c/cGraph.cpp
The UI callback and Dear ImGui for bindingssrc/c/cUi.cpp
Buffers, pipelines, bindless slots, GPU timerssrc/c/cResources.cpp
Animation and morph weightssrc/c/cAnimation.cpp
Engine and asset loader (rasm_c only)src/c/cLoader.cpp
The two shared libraries, their exportssrc/CMakeLists.txt; install in cmake/RasmInstall.cmake
Teststests/cApiTests.cpp (links only rasm_c), tests/cApiHandleTests.cpp, tests/cApiHeaderCheck.c (C99 and C11), tests/c_api/ctypes_smoke.py, tools/check_install.py
The examplesexamples/22_c_api/main.c; examples/33_c_render_graph/main.c (a frame of its own with C passes)
Keep these true
  • Change rasm_c.h only by adding at the end, and bump RASM_C_API_VERSION_MINOR when you do.
  • A new field of a C++ config or desc that C shows goes at the end of its C struct, into the toC and toCpp conversions in src/c/cApi.cpp, and into tests/c_api/ctypes_smoke.py's copy of the struct.
  • Every entry point is a function try block that ends with RASM_C_CATCH, and uses only types from rasm_c.h in its signature.
  • A new entry point that starts a frame, changes a graph or frees what a frame uses calls checkNotRecording.
  • A new value of a C++ enum that C shows gets a C constant and its static_assert.

Further reading