Calling C, and Tern as a library
Tern compiles to C, so it can call C functions directly and C can call Tern. This guide covers both directions: declaring C functions with extern (headers, bundled .c files, libraries, renaming), how each Tern type crosses the boundary, arrays, out-parameters, callbacks, and opaque ptr handles; then export fn, building a static or shared library with a generated header, handling runtime errors from C, and calling in from several threads.
Your first C call
An extern block names a C header and lists the functions you want, with Tern types:
extern "math.h":
fn hypot(a: float, b: float) float
fn pow(x: float, y: float) float
fn main():
print(hypot(3.0, 4.0), pow(2.0, 10.0))5.0 1024.0The header is #included into the generated C, and each call goes through a small wrapper that converts Tern values to their C form. There is no runtime marshalling layer: a call to hypot compiles to a call to hypot.
The signatures are checked against the header by the C compiler, which also converts between compatible types. That is why int (64-bit in Tern) works for a C function that takes or returns a C int or size_t:
extern "string.h":
fn strerror(code: int) str
fn strlen(s: str) int
extern "stdlib.h":
fn getenv(name: str) str
fn atoi(s: str) int
fn main():
print(strerror(2))
print(strlen("héllo"), atoi("42 apples"))
home = getenv("TERN_DOCS_SURELY_UNSET")
print(home == "", len(home))No such file or directory
6 42
true 0strlen("héllo") is 6 because Tern strings are UTF-8 bytes. getenv returns NULL for a missing variable, and a NULL string from C becomes "".
The extern block
extern "header.h" source "impl.c" link "z":
fn name(params) ret
fn tern_name(params) ret = "c_name"Every part after extern is optional:
| Part | What it does |
|---|---|
"header.h" | #include "header.h"; the header's prototypes are used. Headers next to your .tn file are found too. |
source "impl.c" | compile this C file along with the program (path relative to the .tn file; repeatable) |
link "z" | link with -lz. A value starting with - is passed as linker flags as-is (repeatable) |
= "c_name" | call the C function c_name under a different Tern name |
On the command line, -l lib, -L dir, and -I dir do the same for libraries and headers you don't want to name in the source.
Linking a system library (zlib ships with macOS and most Linux systems):
extern "zlib.h" link "z":
fn crc32(crc: int, data: str, n: int) int
fn main():
text = "hello"
print(crc32(0, text, len(text)))907060870Renaming with = "c_name"
Use a rename when the C name clashes with a Tern builtin or reads badly in Tern code. An extern function can't take a builtin's name (abs, min, max, find, copy, ...), so fn abs(n: int) int in an extern block is an error; give it another name instead:
extern "math.h":
fn c_floor(x: float) float = "floor"
extern "stdlib.h":
fn c_abs(n: int) int = "labs"
fn main():
print(c_floor(-2.5), c_abs(-7))-3.0 7Without a header
extern: with no header makes the compiler declare each function itself, using the exact C types from the table below. That's convenient for a function in a C file you compile with source, but the C function must really have those types. llabs takes and returns long long, which is 64-bit, so this is correct:
extern:
fn llabs(n: int) int
fn main():
print(llabs(-42))42Declaring C's abs (which takes a 32-bit int) this way would be wrong, and nothing would catch it. When a header exists, name it.
How types cross the boundary
| Tern parameter | C type | Notes |
|---|---|---|
int | int64_t | with a header, C converts to narrower types |
float | double | |
bool | bool | |
ptr | void* | an opaque C pointer (below) |
str | const char* | valid only during the call; see "Strings" |
[int] / [float] / [byte] | const int64_t* / const double* / const uint8_t* | a pointer to the elements; pass the length separately |
mut int / mut float / mut bool / mut ptr | int64_t* / double* / bool* / void** | an out-parameter; the caller writes &x |
mut [int] / mut [float] / mut [byte] | int64_t* / double* / uint8_t* | C may write the elements |
fn(int) int and similar | int64_t (*)(void*, int64_t) plus void* | a callback: two C arguments (below) |
an extern struct | the C struct (by value), or T* / const T* with mut | converted field by field (below) |
Return types can be int, float, bool, str (or take str, below), ptr, an extern struct, or nothing.
Ordinary Tern structs, enums, maps, [str], arrays of structs, and mut str are compile errors, as is take (moving a value into C means nothing to C):
struct Point:
x, y: float
extern "geom.h" source "geom.c":
fn centroid(pts: [Point], n: int) float
fn rename(name: mut str)
fn main():
pass5: error: `[Point]` can't cross the C boundary (use int, float, bool, str, ptr, [int], [float], [byte], or a function of int/float/bool/ptr values)
6: error: `str` can't cross the C boundary (a `mut` parameter can be int, float, bool, ptr, [int], [float], or [byte])To pass a list of points, pass two [float] arrays (or one array of x, y pairs).
Strings
A str argument arrives in C as a NUL-terminated const char*. When the string has spare capacity for the terminating NUL (string literals always do, and most built strings do), Tern writes the NUL there and passes its own bytes: no copy. Otherwise it passes a temporary copy. Either way the pointer is valid only until the C function returns, and C must not write through it. A string containing a NUL byte looks shorter to C.
A str result is copied into a new Tern string, and NULL becomes "". With a plain str result Tern never frees the pointer C returned, which suits static strings (strerror, getenv) and strings the C library owns. When C hands over memory the caller must free (strdup, most "returns a newly allocated string" functions), declare the result take str: Tern copies it and then calls free() on it.
extern "string.h":
fn strdup(s: str) take str # malloc'd by C, freed by Tern after copying
fn main():
for i in 0..3:
print(strdup(f"copy {i}"))copy 0
copy 1
copy 2A str result stops at the first NUL byte, so binary data (compressed bytes, images, protobuf) comes back as a ptr and a length instead: string_at(p, n) copies the n bytes at p into a Tern string, NUL bytes included (like Python's ctypes.string_at). C still owns the memory; free it with the library's own function afterwards.
extern "stdlib.h":
fn calloc(n: int, size: int) ptr
fn free(p: ptr)
fn main():
p = calloc(4, 1) # four zero bytes
s = string_at(p, 4) # a copy, NULs included
free(p)
print(len(s), s.byte(0), s.byte(3))4 0 0A negative n, or a null p with n > 0, is a runtime error; string_at(p, 0) is "".
Out-parameters with mut
A mut scalar parameter becomes a pointer to the caller's variable. modf splits a float into its whole and fractional parts and returns the whole part through a double*:
extern "math.h":
fn modf(x: float, whole: mut float) float
fn main():
whole = 0.0
frac = modf(3.25, &whole)
print(whole, frac)3.0 0.25The same rules as any mut call apply: &x marks the argument, and one call can't pass the same variable twice.
Arrays
[int], [float], and [byte] pass as a pointer to their first element. C doesn't get the length, so pass len(xs) as its own argument. Read-only arrays are passed as const, with no copy.
With mut, C may write the elements. Arrays are copy-on-write values in Tern, so if the array's storage is shared with another variable, Tern makes it unique first: C's writes change only the array you passed. C can't change the length.
Here is a C file compiled along with the program, and the Tern side. (This page's tests only type-check this program, since they don't have the .c file; the same code runs in tests/run/ffi_source/.)
// stats.h
#include <stdint.h>
void scale(double* xs, int64_t n, double k);
double total(const double* xs, int64_t n);
void minmax(const int64_t* xs, int64_t n, int64_t* lo, int64_t* hi);// stats.c
#include "stats.h"
void scale(double* xs, int64_t n, double k) { for (int64_t i = 0; i < n; i++) xs[i] *= k; }
double total(const double* xs, int64_t n) {
double s = 0;
for (int64_t i = 0; i < n; i++) s += xs[i];
return s;
}
void minmax(const int64_t* xs, int64_t n, int64_t* lo, int64_t* hi) {
for (int64_t i = 0; i < n; i++) {
if (xs[i] < *lo) *lo = xs[i];
if (xs[i] > *hi) *hi = xs[i];
}
}extern "stats.h" source "stats.c":
fn scale(xs: mut [float], n: int, k: float)
fn total(xs: [float], n: int) float
fn minmax(xs: [int], n: int, lo: mut int, hi: mut int)
fn main():
prices = [1.5, 2.0, 4.25]
before = prices # a copy (shares storage until written)
scale(&prices, len(prices), 2.0) # prices is made unique, then C writes it
print(prices, before, total(prices, len(prices)))
xs = [4, -2, 9, 7]
lo = 1000
hi = -1000
minmax(xs, len(xs), &lo, &hi)
print(lo, hi)It prints [3.0, 4.0, 8.5] [1.5, 2.0, 4.25] 15.5 and -2 9: before is unchanged. A field or element works too: scale(&shape.sizes, len(shape.sizes), 2.0).
A [byte] is a C byte buffer (uint8_t*, one byte per element), the usual currency of compression, image, and crypto libraries:
extern "string.h":
fn memset(buf: mut [byte], c: int, n: int) ptr
fn memcmp(a: [byte], b: [byte], n: int) int
fn main():
buf = [byte(0)] * 6
memset(&buf, 42, 4)
same = memcmp(buf, [42, 42, 42, 42, 0, 0], 6) == 0
print(buf, same, buf.to_str()[..4])[42, 42, 42, 42, 0, 0] true ****C structs
Declare a C struct inside the extern block, with the fields you need, as Tern types. = "..." names the C type when it differs ("SDL_Rect", "struct tm"). The struct is an ordinary Tern struct on the Tern side, and crosses to C field by field, so C's own field types are used: an int field holds a Tern int, a float or unsigned char field a Tern float or int, and fields you don't declare are left zero.
extern "time.h":
struct Tm = "struct tm": # the C library's own struct: only these fields are used
tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday: int
fn timegm(t: mut Tm) int # takes `struct tm*`; fills in tm_wday and tm_yday
fn gmtime_r(t: mut int, out: mut Tm) ptr
fn main():
leap_day = Tm(124, 1, 29, 12, 0, 0, 0, 0) # 2024-02-29 12:00 UTC (years since 1900, months from 0)
print(timegm(&leap_day), leap_day.tm_wday, leap_day.tm_yday)
t = 1_000_000_000
out = Tm(0, 0, 0, 0, 0, 0, 0, 0)
gmtime_r(&t, &out)
print(out.tm_year + 1900, out.tm_mon + 1, out.tm_mday, out.tm_hour, out.tm_min)1709208000 4 59
2001 9 9 1 46- By value (
r: Rect) passes the C struct itself; a struct result comes back as a Tern value. mut(r: mut Rect) passes a pointer, which is what most C APIs take,constor not. C's changes are copied back into your variable (or field, or array element) after the call.- Fields can be
int,float,bool,ptr, or anotherexternstruct (nested structs, like a sprite holding a rectangle and a color);tests/run/ffi_structs/has a full example. - Without a header (
extern:), Tern lays the struct out itself from the Tern field types (int64_t,double, ...), so the C side must declare it the same way.
Callbacks: passing Tern functions to C
A parameter with a function type, like f: fn(int) int, becomes two C arguments: a function pointer whose first parameter is a void*, and that void* (the "user data"). C calls the function pointer with the user data first:
// each.h
#include <stdint.h>
int64_t each_sum(int64_t n, int64_t (*f)(void*, int64_t), void* ud);
double integrate(double a, double b, int64_t steps, double (*f)(void*, double), void* ud);// each.c
#include "each.h"
int64_t each_sum(int64_t n, int64_t (*f)(void*, int64_t), void* ud) {
int64_t s = 0;
for (int64_t i = 0; i < n; i++) s += f(ud, i);
return s;
}
double integrate(double a, double b, int64_t steps, double (*f)(void*, double), void* ud) {
double h = (b - a) / (double)steps, s = 0;
for (int64_t i = 0; i < steps; i++) s += f(ud, a + h * ((double)i + 0.5));
return s * h;
}extern "each.h" source "each.c":
fn each_sum(n: int, f: fn(int) int) int
fn integrate(a: float, b: float, steps: int, f: fn(float) float) float
fn main():
k = 3
print(each_sum(5, fn(i) i * k)) # a closure: it captured k
print(integrate(0.0, 1.0, 1000, fn(x) x * x))Any Tern function value works: a lambda, a closure that captured variables, a nested fn, or a top-level function. The user data is the closure itself, so C libraries that follow the common "function pointer plus void* context" convention can call back into Tern directly.
Rules for callbacks:
- Their parameters and result must be
int,float,bool, orptr(or no result).fn(str) intcan't be a callback. - Lifetime: C may call the function only while the call it was passed to is running. Don't store the function pointer or user data for later: the closure may be freed as soon as the call returns.
- Threads: in a normal build, C must call it on the same thread that made the call. If the C code calls back from threads of its own (a C library that parallelizes a loop, say), build with
--portable, where any thread can run Tern code. Libraries (--lib,--shared) always use the portable runtime. Without--portable, a callback that allocates on another thread crashes.
Opaque handles: ptr
ptr is a C pointer that Tern only stores and passes along: a FILE*, a database connection, an object from a C library. null is the null pointer, p.is_null() tests for it, and == compares two pointers. With a header, C converts between void* and the real pointer type for you:
import fs
extern "stdio.h":
fn fopen(path: str, mode: str) ptr
fn fputs(text: str, f: ptr) int
fn fclose(f: ptr) int
fn write_lines(path: str, lines: [str]) bool:
f = fopen(path, "w")
if f.is_null():
return false
for line in lines:
fputs(line + "\n", f)
fclose(f)
return true
fn main():
path = "/tmp/tern_c_interop.txt"
print(write_lines(path, ["alpha", "beta"]))
print(fs.read(path).trim())
print(write_lines("/no/such/dir/x.txt", ["lost"]))
fs.remove(path)true
alpha
beta
falsePass null where C accepts a null pointer:
extern "time.h":
fn time(out: ptr) int
fn main():
now = time(null)
print(now > 1700000000)trueA ptr is a plain value: copying it copies the address, and a struct may hold one. Tern never frees what it points to, so call the library's close or free function yourself (fclose above). null has type ptr only; other types have no null.
Tern as a library: export fn
The other direction: mark functions export fn, and C (or anything that can call C: Swift, Kotlin through JNI, Python's ctypes) can call them.
export fn word_count(text: str) int:
n = 0
for w in text.split(" "):
if len(w) > 0:
n += 1
return n
export fn shout(text: str) str:
return text.upper() + "!"
export fn nth_word(text: str, i: int) str:
return text.split(" ")[i]
fn main():
print(word_count("the quick brown fox"), shout("hi"), nth_word("a b c", 1))4 HI! bA library doesn't need fn main(); if it has one (handy for trying the functions with tern run), library builds leave it out. Exported functions take int, float, bool, str, or ptr parameters (read-only; no mut or take) and return one of those or nothing. Only the main file can export. Everything else in the program (structs, arrays, parallel, other modules) works as usual behind the exported functions.
Build it:
tern build --lib words.tn -o libwords.a # static library + words.h
tern build --shared words.tn -o libwords.dylib # shared (.so on Linux) + words.hThe header is named after the library (libwords.a gives words.h) and written next to it:
// words.h: generated by ternc. Functions exported from a Tern library.
// link with: -lm -lpthread
...
int64_t word_count(const char* text);
char* shout(const char* text); // returns a malloc'd string: free it with tern_free()
char* nth_word(const char* text, int64_t i); // can fail: check tern_last_error(); returns a malloc'd string: free it with tern_free()
// After a call to a function marked "can fail": the message of its runtime error, or NULL.
// (A runtime error returns 0 / NULL / false from the call instead of ending the process.)
const char* tern_last_error(void);
void tern_free(void* p);
void* tern_alloc(int64_t n);
void tern_stats(void); // print memory statistics (builds made with TERN_STATS=1)A C program using it:
#include <stdio.h>
#include "words.h"
int main(void) {
printf("%lld\n", (long long)word_count("tern compiles to c"));
char *s = shout("hello");
printf("%s\n", s);
tern_free(s);
char *w = nth_word("red green blue", 7);
if (w == NULL)
printf("error: %s\n", tern_last_error());
return 0;
}cc host.c -I. libwords.a -lm -lpthread -o host && ./host4
HELLO!
error: runtime error (line 12): index 7 out of bounds (length 3)Strings across an export
- A
const char*argument is copied into a Tern string;NULLis treated as"". The caller keeps ownership of its string. - A
strresult is a newmalloc'd, NUL-terminatedchar*that the caller owns. Free it withtern_free()(which callsfree, but using it keeps working if that ever changes).
Runtime errors
A runtime error that would end a normal program (an index out of bounds, a missing map key, division by zero, pop() on an empty array) doesn't end the host process. The call returns 0, 0.0, false, or NULL, and tern_last_error() returns the message, just like the message a program would print. The library keeps working for later calls.
- The compiler works out which exported functions can fail, and marks them in the header with
can fail: check tern_last_error(). Functions that can't fail (word_countandshoutabove) skip the error-catching setup entirely, so they cost no more than a plain C call. - A function that can fail clears the error at the start of each call, so check
tern_last_error()right after that call. Functions that can't fail don't touch it. - The error is per thread: a failure on one thread doesn't show up on another.
- Values the failing call had built are abandoned, not freed, so each error leaks a little memory. Treat errors as exceptional, not as control flow; for expected failures, return a status (
-1,"", or abool) from Tern code instead.
Threads and startup
There is no init function to call. The Tern runtime starts on the first call into the library, on whichever thread makes it, and several host threads may call exported functions at the same time. parallel blocks inside an exported function run on Tern's own worker threads, as in a normal program. examples/embed/ shows a C program calling a Tern library from two threads:
examples/embed/run.shdescribe: 8 numbers, total 31, largest 9
squares_total(1000) = 332833500
thread: sum_csv("1,2,3") x 2000 = 12000
thread: sum_csv("10,20,30") x 2000 = 120000
nth(1) = 6, error: none
nth(10) = 0, error: runtime error (line 40): index 10 out of bounds (length 3)
still running: sum_csv = 42Libraries use the portable runtime, which finds each thread's heap through thread-local storage instead of from the stack. That's what lets Tern code run on threads it didn't create. It costs about 20% on allocation-heavy code and nothing measurable otherwise.
Other hosts
The library is plain C, so anything with a C FFI can load it. tests/embed/py_host.sh loads a --shared build from Python with ctypes:
import ctypes
lib = ctypes.CDLL("./libstats.so")
lib.describe.restype, lib.describe.argtypes = ctypes.c_void_p, [ctypes.c_char_p]
lib.tern_last_error.restype = ctypes.c_char_p
p = lib.describe(b"7,8")
print(ctypes.string_at(p).decode())
lib.tern_free(ctypes.c_void_p(p))Declare string results as c_void_p, not c_char_p, so you keep the pointer to free. For Swift and Kotlin, see iOS and Android; for JavaScript, see WebAssembly and JavaScript.
Performance
Crossing the boundary is cheap in both directions. From bench/platforms_results.md (Apple M4 Pro, median of 5 runs, against the same programs in Rust):
| benchmark | Tern | Rust |
|---|---|---|
| calling C: 200M calls + 5M string arguments | 200ms | 245ms |
| called from C: 200M calls + 2M string calls | 392ms | 428ms |
Strings go to C without a copy when they have room for the NUL, and exported functions that can't fail skip error handling. Both are small effects; the point is that a C call is a C call.
Limits
- Only
int,float,bool,str,ptr,[int],[float],[byte],externstructs of those, and callbacks of scalar values cross the boundary. C unions, fixed-size arrays inside C structs, and arrays of structs don't: use aptrto C-side data with accessor functions. - Exported functions take and return only
int,float,bool,str, andptr. - A callback must be called during the call it was passed to, and, without
--portable, on the same thread. extern:without a header trusts your signatures; a mismatch with the real C function is undefined behavior that nothing reports.- C code runs outside Tern's safety checks. A C function that writes past an array's end or keeps a string pointer after returning can corrupt memory like in any C program.