DEV Community

Cover image for Calling C from KingCobra: a hands-on FFI tutorial
Divyanshu Sinha
Divyanshu Sinha

Posted on

Calling C from KingCobra: a hands-on FFI tutorial

KingCobra can call C code directly, with no binding generator and no glue files. This tutorial covers the two ways to do it, how values cross the boundary, how to write and load your own C library, and where the language's safety checks stop. Every example was run on KingCobra 1.0.0, and the output shown is the real output.

You should know the basics of KingCobra (see the language tutorial) and be able to read simple C.

Setup

You need KingCobra, and from section 6 onwards a C compiler. KingCobra runs on Linux, macOS and Windows, and every program in this tutorial is the same source on all three, apart from the library file names covered in section 6.

KingCobra

# Windows (PowerShell as Administrator)
choco install kingcobra
Enter fullscreen mode Exit fullscreen mode
# Linux and macOS
curl -fsSL https://github.com/DivyanshuSinha136/kingcobra/releases/latest/download/install.sh | sh
Enter fullscreen mode Exit fullscreen mode

Scoop, the no-admin PowerShell installer and building from source are covered in the language tutorial. After installing, open a new terminal and run kingcobra version. Run any example in this tutorial with kingcobra run file.kc.

A C compiler (for the libraries you build yourself)

Platform Compiler
Linux cc from gcc or clang (on Debian and Ubuntu: sudo apt install build-essential)
macOS cc from the Xcode command line tools (xcode-select --install)
Windows MinGW-w64 gcc (for example from MSYS2), or MSVC cl from an "x64 Native Tools Command Prompt"

Tip for Windows: if non-ASCII text looks garbled in cmd.exe (for example an em dash printing as ΓÇö), the console is using an old code page. Run chcp 65001 first, or use Windows Terminal, which uses UTF-8 by default.

1. Two ways to call C

extern fn (declared) native import (inferred)
Syntax extern fn abs(x: int) -> int from "libc.so.6"; import "./libmylib.so" as lib;
You write a signature for each function nothing, the library is opened as a whole
Types taken from your declaration guessed from the arguments you pass
Works with any shared library .so, .dll, .dylib, or a .o compiled with -fPIC
Best for libc, libm and other system libraries, pointer arguments your own small C libraries with simple signatures

The rule of thumb: declare what you can, import what's convenient. Declared externs say exactly what you mean, and inferred imports can quietly get a signature wrong (section 7).

2. Your first foreign call

extern fn abs(x: int) -> int from "libc.so.6";
extern fn sqrt(x: float) -> float from "libm.so.6";
extern fn floor(x: float) -> float from "libm.so.6";

fn main() {
    print(abs(-42));
    print(sqrt(2.0));
    print(floor(2.7));
}
Enter fullscreen mode Exit fullscreen mode
42
1.41421
2
Enter fullscreen mode Exit fullscreen mode

An extern fn declaration names the C symbol, gives its parameter and return types, and says which library to find it in. After that you call it like any KingCobra function. A function declared -> void returns null.

Library names. On Linux, the C library is libc.so.6 and the math library is libm.so.6. On Windows, KingCobra maps those two names to the C runtime DLLs (ucrtbase.dll or msvcrt.dll), so the same source runs on both. On macOS the interpreter loads names as written, so use the macOS library names there (for example libSystem.B.dylib for the C library).

3. Passing strings

A KingCobra string argument is passed to C as a char *:

extern fn strlen(s: string) -> int from "libc.so.6";
extern fn atoi(s: string) -> int from "libc.so.6";
extern fn toupper(c: int) -> int from "libc.so.6";

fn main() {
    print(strlen("hello, FFI"));
    print(atoi("1234") + 1);
    print(chr(toupper(ord("k"))));
}
Enter fullscreen mode Exit fullscreen mode
10
1235
K
Enter fullscreen mode Exit fullscreen mode

Characters are ints in KingCobra, so toupper takes and returns an int. ord and chr convert between a one-character string and its code point.

4. Floats, and the "same kind" rule

Floats work too, as long as the declaration is consistent:

extern fn pow(x: float, y: float) -> float from "libm.so.6";
extern fn hypot(x: float, y: float) -> float from "libm.so.6";

fn main() {
    print(pow(2.0, 10.0), hypot(3.0, 4.0));
}
Enter fullscreen mode Exit fullscreen mode
1024 5
Enter fullscreen mode Exit fullscreen mode

Now the limitation. The interpreter's FFI passes arguments in fixed-arity trampolines, so all parameters of one extern must be the same kind: all int-like, or all float-like. C's ldexp(double x, int e) mixes the two:

extern fn ldexp(x: float, e: int) -> float from "libm.so.6";
fn main() { print(ldexp(1.0, 3)); }
Enter fullscreen mode Exit fullscreen mode
f3b.kc:1:1: error: extern 'ldexp': v0.1 FFI requires all parameters to be the same kind (all int-like or all float-like); mixed signatures need libffi (see ROADMAP)
    1 | extern fn ldexp(x: float, e: int) -> float from "libm.so.6";
      | ^
Enter fullscreen mode Exit fullscreen mode

The error appears when the declaration is read, before anything runs. Two ways around it:

  • Wrap it in C. Write a small C function with a uniform signature (for example double ldexp_f(double x, double e)) and call that.
  • Compile with kcc. The compiler (section 10) does full calling-convention handling, and ldexp(1.0, 10) works there.

Other limits of declared externs: at most 6 parameters, and arguments can be ints, bools, strings, floats, pointers or buffers.

A C int is 32 bits, and KingCobra's is 64

KingCobra reads an -> int result as a full 64-bit value. A C function that returns a 32-bit int only fills the lower half of the register, so a negative result can come back as a huge positive number. strcmp returns a negative int when the first string sorts first:

extern fn strcmp(a: string, b: string) -> int from "libc.so.6";
fn main() {
    print(strcmp("apple", "banana"));
    print(strcmp("apple", "banana") as i32);
    print(strcmp("b", "a"), strcmp("a", "a"));
}
Enter fullscreen mode Exit fullscreen mode
4294967295
-1
1 0
Enter fullscreen mode Exit fullscreen mode

The cast as i32 reinterprets the lower 32 bits as a signed value, which gives you the answer C meant. Use it whenever a C function returns an int that can be negative, and as u32, as i16 and so on for the other widths. Functions that return long or int64_t, as in your own libraries from section 6, don't need it. Exact values for results like strcmp's can differ between C libraries, but the cast gives you the right sign on every platform.

5. Pointers and buffers: where unsafe begins

KingCobra checks every pointer you make itself: bounds, lifetime, null. C does none of that. So the moment a pointer or buffer crosses into native code, you have to say so with an unsafe { } block.

extern fn memset(p: *u8, v: int, n: int) -> *u8 from "libc.so.6";

fn main() {
    let buf = buffer(8);
    memset(buf.ptr, 7, 8);
    print("unreachable");
}
Enter fullscreen mode Exit fullscreen mode
f4b.kc:4:5: error: passing a pointer or buffer to native code requires an `unsafe { }` block (native code is not bounds-checked)
    4 |     memset(buf.ptr, 7, 8);
      |     ^
Enter fullscreen mode Exit fullscreen mode

Add the block and it works. Here C allocates memory and KingCobra reads it:

extern fn malloc(n: int) -> *u8 from "libc.so.6";
extern fn memset(p: *u8, v: int, n: int) -> *u8 from "libc.so.6";
extern fn free(p: *u8) -> void from "libc.so.6";

fn main() {
    // C hands us a raw pointer, so every dereference needs unsafe
    unsafe {
        let c = malloc(16);
        memset(c, 0x41, 15);
        c[15] = 0;
        print(c.read_cstr());
        free(c);
    }
}
Enter fullscreen mode Exit fullscreen mode
AAAAAAAAAAAAAAA
Enter fullscreen mode Exit fullscreen mode

An extern declared -> *u8 returns a raw pointer: dereferencing it needs unsafe, and KingCobra can't know how big it is. read_cstr() reads a NUL-terminated string from it.

The safer direction is to give C one of your buffers to fill:

extern fn strncpy(dst: *u8, src: string, n: int) -> *u8 from "libc.so.6";
extern fn strlen(p: *u8) -> int from "libc.so.6";

fn main() {
    let buf = buffer(32);
    unsafe {
        strncpy(buf.ptr, "copied by libc", 31);
        print(strlen(buf.ptr));
    }
    print(buf.to_string(0, 14));
}
Enter fullscreen mode Exit fullscreen mode
14
copied by libc
Enter fullscreen mode Exit fullscreen mode

The buffer is allocated and freed by KingCobra, so you don't have to match a malloc with a free. The buffer also remembers its size, so everything you do with it outside unsafe stays bounds-checked.

Known issue in 1.0.0: a return inside an unsafe { } block doesn't leave the function, and the function returns null. Assign the result to a variable inside the block and return it after the block, as in section 9. That pattern is correct on every version.

6. Writing your own C library

Here is a small library for the rest of the tutorial. Save it as mylib.c:

/* mylib.c: a small native library for the FFI tutorial.
 * Uses fixed-width integer types so the same file works on Linux, macOS and
 * Windows (where `long` is only 32 bits). */
#include <stdint.h>

#if defined(_WIN32)
  #define EXPORT __declspec(dllexport)
#else
  #define EXPORT
#endif

EXPORT int64_t add(int64_t a, int64_t b)       { return a + b; }
EXPORT int64_t factorial(int64_t n)            { int64_t r = 1; while (n > 1) r *= n--; return r; }
EXPORT double  half(double x)                  { return x / 2.0; }
EXPORT double  hypot2(double a, double b)      { return a * a + b * b; }

/* takes ints, returns a double: the inferred-signature trap (section 7) */
EXPORT double  mean2(int64_t a, int64_t b)     { return (double)(a + b) / 2.0; }

/* the fix: take doubles when you return a double */
EXPORT double  mean2f(double a, double b)      { return (a + b) / 2.0; }

/* sums n 64-bit integers behind a pointer */
EXPORT int64_t sum_array(const int64_t *p, int64_t n) {
    int64_t t = 0;
    for (int64_t i = 0; i < n; i++) t += p[i];
    return t;
}

/* fills a caller-provided struct { int32 id; int32 score; int64 total; } (16 bytes) */
typedef struct { int32_t id; int32_t score; int64_t total; } Record;
EXPORT int64_t fill_record(Record *r, int64_t id) {
    r->id = (int32_t)id; r->score = (int32_t)(id * 10); r->total = id * 1000;
    return 0;
}

/* returns a static C string */
EXPORT const char *greeting(void) { return "hello from C"; }
Enter fullscreen mode Exit fullscreen mode

Two portability details in that file matter for FFI in general:

  • Use int64_t, not long. KingCobra integers are 64-bit. long is 64 bits on Linux and macOS but only 32 bits on Windows, so a long parameter would read the wrong half of the value there.
  • Export your functions on Windows. A DLL only exposes functions marked __declspec(dllexport). The EXPORT macro does that on Windows and does nothing elsewhere.

Build it for your platform

Platform Library file Build command
Linux libmylib.so cc -shared -fPIC -o libmylib.so mylib.c
macOS libmylib.dylib cc -dynamiclib -o libmylib.dylib mylib.c
Windows (MinGW-w64) mylib.dll gcc -shared -o mylib.dll mylib.c
Windows (MSVC) mylib.dll cl /LD mylib.c /Fe:mylib.dll

The examples below use the Linux name, ./libmylib.so. On macOS, write ./libmylib.dylib; on Windows, write ./mylib.dll. Nothing else changes.

Import it

No declarations are needed:

import "./libmylib.so" as lib;

fn main() {
    print(lib.add(40, 2));
    print(lib.factorial(10));
    print(lib.half(7.0));
    print(lib.hypot2(3.0, 4.0));
}
Enter fullscreen mode Exit fullscreen mode
42
3628800
3.5
25
Enter fullscreen mode Exit fullscreen mode

The output is identical on all three platforms, because only the file name differs:

import "./libmylib.dylib" as lib;     // macOS
import "./mylib.dll" as lib;          // Windows
Enter fullscreen mode Exit fullscreen mode

How a native import decides the signature: every call looks the symbol up and infers the calling convention from the arguments you actually pass. If all arguments are int-like, everything is treated as 64-bit ints, including the result. If the first argument is a float, everything is treated as doubles.

Path rules:

  • Use a path with a directory in it (./libmylib.so), not a bare name (libmylib.so). A bare name goes to the system loader, which doesn't search your folder, and fails with cannot open shared object file.
  • A native import's path is resolved relative to the importing file, so the program above also runs when you start it from another directory.
  • A .o object file also works, if it was compiled with -fPIC and you have a C compiler on your PATH (cc -fPIC -c mylib.c -o mylib.o, then import "./mylib.o" as lib;). KingCobra links it into a mylib.kcnative.so next to it on first use.

One program, three platforms

Library paths are string literals, so a program can't switch between them on its own. The simplest portable layout is one tiny wrapper module per platform that differs only in the file name, with the rest of your code importing whichever one belongs to the OS it runs on:

// native_linux.kc
import "./libmylib.so" as lib;
Enter fullscreen mode Exit fullscreen mode
// native_macos.kc
import "./libmylib.dylib" as lib;
Enter fullscreen mode Exit fullscreen mode
// native_windows.kc
import "./mylib.dll" as lib;
Enter fullscreen mode Exit fullscreen mode

The wrapper module in section 9 names the library in two places (the import and the extern). Keep one copy per platform with just that file name changed, and everything above it stays the same.

7. The inferred-signature trap

This is the most important gotcha in the whole FFI. Look at mean2 in the C file: it takes two int64_ts and returns a double. Import it and call it with ints:

import "./libmylib.so" as lib;

fn main() {
    print(lib.mean2(3, 4));        // C says 3.5
    print(lib.mean2(10, 20));      // C says 15.0
}
Enter fullscreen mode Exit fullscreen mode
7
30
Enter fullscreen mode Exit fullscreen mode

Both results are wrong, and nothing warned you. All-int arguments told KingCobra to read an integer result, but a double comes back in a different register, so it picked up leftover integer garbage (here the sum of the arguments).

The fix is on the C side: if a function returns a double, make it take doubles. mean2f does exactly that:

import "./libmylib.so" as lib;
fn main() { print(lib.mean2f(3.0, 4.0), lib.mean2f(10.0, 20.0)); }
Enter fullscreen mode Exit fullscreen mode
3.5 15
Enter fullscreen mode Exit fullscreen mode

General rules to keep inferred imports safe:

  • Functions that take and return ints, or take and return doubles, are safe.
  • A function that takes ints and returns a float, or takes floats and returns an int, is not. Change the C signature, or wrap it.
  • Functions that return a 32-bit int which can be negative need as i32 on the result (section 4).
  • Pointer arguments belong to declared externs (next section).

8. Pointers, structs and strings from your own library

For anything beyond plain numbers, declare the externs. This program sums an array in C, has C fill a struct, and reads a C string:

extern fn sum_array(p: *u8, n: int) -> int from "./libmylib.so";
extern fn fill_record(r: *u8, id: int) -> int from "./libmylib.so";
extern fn greeting() -> *u8 from "./libmylib.so";

fn main() {
    // an array of five 64-bit integers in a checked buffer
    let nums = buffer(5 * 8);
    for (i in 0..5) { nums.put_i64(i * 8, (i + 1) * 10); }
    unsafe { print(sum_array(nums.ptr, 5)); }          // 10+20+30+40+50

    // C writes a struct { int32 id; int32 score; int64 total; } into our buffer
    let rec = buffer(16);
    unsafe { fill_record(rec.ptr, 7); }
    print(rec.get_i32(0), rec.get_i32(4), rec.get_i64(8));

    // C returns a pointer to a static string
    unsafe { print(greeting().read_cstr()); }
}
Enter fullscreen mode Exit fullscreen mode
150
7 70 7000
hello from C
Enter fullscreen mode Exit fullscreen mode

How it fits together:

  • Arrays. Lay out the elements yourself with put_i64(offset, value). The element size and offset are your responsibility, because C won't check them.
  • Structs. C's struct { int32_t id; int32_t score; int64_t total; } has id at offset 0, score at offset 4 and total at offset 8, 16 bytes in all. Allocate a buffer of that size, pass buf.ptr, and read the fields back with get_i32 and get_i64. Keep the offsets in sync with your C header. The language reference (docs/POINTERS.md) shows how to describe C-layout structs with struct, sizeof and offsetof.
  • Returned strings. A -> *u8 result is a raw pointer. read_cstr() reads up to the NUL terminator, and it needs unsafe.

One path difference. A declared extern's from "./libmylib.so" is looked up relative to the current working directory, not to the source file. Run the program from the folder that holds the library, use an absolute path, or install the library where the system loader finds it. (A native import, by contrast, resolves relative to the importing file.) On macOS and Windows the file name changes the same way as in section 6.

9. Wrap it: a safe KingCobra module around C

The best habit in FFI work is to keep unsafe small and hide it behind a normal function that checks its inputs. Save this as cmath.kc:

// cmath.kc: a safe KingCobra wrapper around the C functions in libmylib.so
import "./libmylib.so" as c;

extern fn sum_array(p: *u8, n: int) -> int from "./libmylib.so";

/// Sum an array of ints using the C implementation.
fn sum(xs: int[]) -> int {
    if (len(xs) == 0) { return 0; }
    let b = buffer(len(xs) * 8);
    defer b.free();                       // freed on every exit path
    for (i, x in xs) { b.put_i64(i * 8, x); }
    var total = 0;
    unsafe { total = sum_array(b.ptr, len(xs)); }
    return total;
}

/// Mean of two numbers (the C side takes doubles).
fn mean(a: float, b: float) -> float { return c.mean2f(a, b); }
Enter fullscreen mode Exit fullscreen mode

On macOS or Windows, change the library file name in the two places it appears (./libmylib.dylib or ./mylib.dll).

import "cmath.kc" as cm;

fn main() {
    print(cm.sum([1, 2, 3, 4, 5]));
    print(cm.sum([]));
    print(cm.mean(3.0, 4.0));
}
Enter fullscreen mode Exit fullscreen mode
15
0
3.5
Enter fullscreen mode Exit fullscreen mode

What the wrapper buys you:

  • Callers pass a normal array and never see a pointer.
  • The buffer size comes from len(xs), so it can't drift out of sync with the element count.
  • defer b.free() releases the buffer on every exit path, including an error.
  • The empty-array case is handled before C ever sees it.
  • The unsafe block is one line, and the result is assigned to a variable and returned afterwards (see the known issue in section 5).
  • kingcobra check cmath.kc still type-checks the module.

10. Calling C from compiled programs with kcc

Everything above runs in the interpreter. kcc, the KingCobra compiler written in KingCobra, turns a program into a native executable, and its extern fn support is different: calls go through the loader's normal import table, and the calling convention follows the platform ABI. That includes mixed int and float signatures, which the interpreter rejects.

extern fn puts(s: *u8) -> int from "libc.so.6";
extern fn ldexp(x: float, e: int) -> float from "libm.so.6";
extern fn abs(x: int) -> int from "libc.so.6";

fn main() -> int {
    puts("hello from a compiled KingCobra program");
    print(abs(-7));
    print(ldexp(1.0, 10));
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
kcc app.kc -o app
./app
Enter fullscreen mode Exit fullscreen mode
kcc: wrote app (5208 bytes, linux executable)
hello from a compiled KingCobra program
7
1024
Enter fullscreen mode Exit fullscreen mode

The executable is 5,208 bytes. ldd ./app shows that it links directly against libc.so.6 and libm.so.6, and the mixed-signature ldexp(1.0, 10) returns 1024 as it should. For Windows and macOS targets, kcc translates libc.so.6 to msvcrt.dll and libSystem.B.dylib, so one source file builds for all three (--target linux|windows|macos).

11. What the FFI can't do (yet)

In 1.0.0:

  • Callbacks. You can't pass a KingCobra function to C. For example, qsort can't take a comparator:
  f10.kc:5:14: error: extern 'qsort': argument 4 must be int, bool, or string
Enter fullscreen mode Exit fullscreen mode
  • More than 6 parameters (interpreter):
  error: extern 'f': KingCobra's native FFI supports at most 6 parameters
Enter fullscreen mode Exit fullscreen mode
  • Mixed int/float parameters (interpreter, section 4). kcc handles them.
  • Structs by value. Pass a pointer to a buffer, as in section 8. The roadmap lists full ABI marshalling for the interpreter as planned work.

12. Errors you will see

Message Cause and fix
symbol 'nosuch_function' not found: ... undefined symbol: nosuch_function The library loaded but doesn't contain that name. Check spelling, and that you didn't compile C++ without extern "C".
could not load library 'libnope.so': ... cannot open shared object file The library isn't where the loader looks. Use ./ for a native import, run from the right folder for a declared extern, or use an absolute path.
'abs' expects 1 argument(s), got 2 The call doesn't match your declaration. This is checked before C is called.
passing a pointer or buffer to native code requires an unsafe { } block Wrap the call in unsafe { }.
v0.1 FFI requires all parameters to be the same kind Mixed int and float parameters (section 4).

13. The safety boundary, plainly

KingCobra's memory checks end where C begins. Native code can read or write anywhere, and a crash inside C can't be caught. This program tries to catch it:

extern fn strlen(s: int) -> int from "libc.so.6";
fn main() {
    try { print(strlen(0)); } catch (e) { print("caught"); }
    print("after");
}
Enter fullscreen mode Exit fullscreen mode

Passing a null pointer to strlen makes C crash, and the whole process dies with Segmentation fault (exit code 139). Neither caught nor after is printed.

So the habits that keep FFI code safe are:

  1. Keep unsafe blocks to a line or two, and put them inside wrapper functions that validate their inputs (section 9).
  2. Prefer KingCobra buffers over malloc, so memory is freed by the runtime, and use defer for anything C allocates.
  3. Check sizes in KingCobra before calling C, since C won't check them for you.
  4. Test the C library separately. A bug in your C code will look like a mysterious KingCobra crash.
  5. Run kingcobra --leaks to catch KingCobra-side buffers you forgot to free.

Where to go next

  • docs/POINTERS.md: the pointer, buffer and struct-layout reference
  • docs/KCC.md: compiling to native executables, and the freestanding target
  • examples/std_ffi.kc and examples/native_import_demo.kc: the shortest runnable FFI examples in the repo
  • Repo: https://github.com/DivyanshuSinha136/KingCobra

If you hit a wall the FFI can't get past, or find a signature that behaves differently from what's described here, open an issue.

Top comments (0)