Skip to content
Kavachकवच

A Library for Any Language

Also known as: shared library dll so dylib ctypes ffi embed python node java go csharp binding header

● Advanced4 minBefore this: Modules: pub

kavach build --lib turns Kavach code into a shared library with a C header, which Python, Node.js, Java, Go and C# can load like any other.

pub fn add(a: Int, b: Int) -> Int {
    a + b
}

pub fn greet(name: String) -> String {
    "hello, {name}"
}
mathlib.kav: Kavach code

kavach build --lib mathlib.kav writes the library and this header, word for word:

/* mathlib.h: the C interface of the Kavach library `mathlib`,
   made by `kavach build --lib` (spec 10.10). */

#ifndef MATHLIB_H
#define MATHLIB_H

#include <stdbool.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

int64_t mathlib_add(int64_t a, int64_t b);
char* mathlib_greet(const char* name);

/* Frees text this library gave (a `char*` result). */
void mathlib_free(char* text);
/* The last error, as text to free with mathlib_free; null before any. */
char* mathlib_last_error(void);

#ifdef __cplusplus
}
#endif

#endif
out/mathlib.h: C code
  • Each pub function becomes a C function, named after the library: mathlib_add. What isn't pub stays inside.
  • Any language that can call C can call it: Python's ctypes, Node-API, JNI, cgo, P/Invoke.
  • Text the library gives back is freed with mathlib_free; an error's reason comes from mathlib_last_error.

You don't have to rewrite a system to use Kavach in it: write the fast or safety-critical part in Kavach, and call it from the code you have. The repository's own test does exactly this from Python.