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.
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.
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.
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.
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.
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
For a few big, long-lived objects with create and destroy calls. The layout can change freely.
Integer handle
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
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.
Booleans
C99 bool is one byte, but C# marshals a bool as four. A uint32_t is the same everywhere.
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.
Three kinds of call read the size differently:
- Create: fields past the caller's size take their defaults.
- Update: fields past it keep the object's current values, so an old program does not reset a new setting it never saw.
- Get: the library writes only up to the caller's size.
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.
6Errors without exceptions
- Check every pointer, size and enum value at the line: a bad argument is a code, never a crash.
- Call the C++ code inside
try. - Catch every exception: out of memory becomes its own code, anything else an internal error.
- 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.
In: borrowed
Strings, arrays and structs are read during the call only. The library copies what it keeps.
Out: the caller's buffer
The snprintf rule: write what fits, return the full length. Call once with no buffer to learn the size.
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.
A callback crosses the line in the other direction, so the same rules hold the other way round, and a few more:
| Rule | Why |
|---|---|
| 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
- 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
trythat 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.
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
| Part | This page | RASM |
|---|---|---|
| Big objects | opaque pointers | rasm_renderer, rasm_engine, rasm_asset_loader, rasm_image. An engine's renderer and loader belong to it. |
| Small objects | integer 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 booleans | uint32_t | The 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 structs | a size field and init functions | The 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. |
| Errors | codes and a per-thread last error | rasm_result, rasm_get_last_error, and rasm_set_log_callback. RASM's spdlog::error lines feed the last error too. |
| Versions | refuse another major, or a newer minor | The 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). |
| Callbacks | a function pointer, user_data, handles live during the call | rasm_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 structs | step by the first element's size | rasm_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. |
| Exports | only the C names | Only rasm_*; tools/check_install.py checks the export tables in CI. |
| Data files | beside the library | Relative 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
| What | Where |
|---|---|
| The header | include/rasm/rasm_c.h |
| Checks, conversions, the log sink, the version check | src/c/cApi.h, src/c/cApi.cpp |
| Renderer, frame, readback, images | src/c/cRenderer.cpp |
| Scenes, entities, meshes, materials, textures, lights, cameras | src/c/cScene.cpp |
| Windows, input events, camera controllers, rigs and input states | src/c/cInput.cpp |
| Views and render targets | src/c/cViews.cpp |
| The render graph, pass callbacks and commands | src/c/cGraph.cpp |
| The UI callback and Dear ImGui for bindings | src/c/cUi.cpp |
| Buffers, pipelines, bindless slots, GPU timers | src/c/cResources.cpp |
| Animation and morph weights | src/c/cAnimation.cpp |
Engine and asset loader (rasm_c only) | src/c/cLoader.cpp |
| The two shared libraries, their exports | src/CMakeLists.txt; install in cmake/RasmInstall.cmake |
| Tests | tests/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 examples | examples/22_c_api/main.c; examples/33_c_render_graph/main.c (a frame of its own with C passes) |
- Change
rasm_c.honly by adding at the end, and bumpRASM_C_API_VERSION_MINORwhen you do. - A new field of a C++ config or desc that C shows goes at the end of its C struct, into the
toCandtoCppconversions insrc/c/cApi.cpp, and intotests/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 fromrasm_c.hin 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
- The System V AMD64 ABI and Microsoft's x64 calling convention: how C arguments and structs travel in registers.
- The Vulkan specification, "Valid Usage for Structure Types":
sTypeandpNext, another way to grow structs. - Microsoft, "Using the cbSize member": the size-field pattern in Win32.
- Ulrich Drepper, How To Write Shared Libraries (2011): symbol visibility and export control.