Basic C3 FFI

A simple example that shows how effortless you can call C functions from C3. I’m not even sure if the term Foreign Function Interface is appropriate here, because calling C functions does not feel foreign at all.

For me the c3c command in the Makefile is the most important part of the whole demonstration. It was provided to me by the author of the C3 language in the discord channel only minutes after I asked that question. Very nice!

c3c compile-only -O1 -o c3math c3math.c3 --single-module=yes

Sources

c3math.c3

module c3math;

fn int square2(int x) @export("square") {
    return x * x;
}

main.c

#include <stdio.h>

extern int square(int);

int main() {
    // call square in C
    int res = square(11);
    printf("%d\n", res);
    return 0;
}



stubs_c3math.c

#include <stdio.h>
#define CAML_NAME_SPACE
#include <caml/mlvalues.h>
#include <caml/memory.h>

extern int square(int);


CAMLprim value caml_square(value number_val){
    int number = Int_val(number_val);
    printf("Stub arg: %i\n", number);
    int res = square(number);
    printf("Stub res: %i\n", res);
    return Val_int(res);
}

Makefile

.PHONY: all clean 

all: main
    ./main

main:
    c3c compile-only -O1 -o c3math c3math.c3 --single-module=yes
    gcc -o main c3math.o main.c


clean:
    rm -f main
    rm -f *.o
    rm -f *.out
    rm -f *.a
    rm -f *.dylib
    

Downloads

basic-c3-ffi_20240830020641.zip