Basic Ocaml ffi with c library

In the previous article I just showed the most basic and simple way to call C from Ocaml. Read more about here ./basic-ocaml-ffi_20240828121852.html.

So this is another basic example that shows how to call into a C function from Ocaml. This time the C function exists in its own library source file inclusive a header file.

The base and starting point for this article is again an article on StackOverflow.com under https://stackoverflow.com/questions/57029419/unresolved-external-function-while-linking-ocaml-and-c

Sources

basicmath.c


int plusone(int number){
    return ++number;
};

basicmath.h

int plusone(int number);

main.ml

external plusone: int -> int = "caml_basicmath_plusone"

let _ = print_int(plusone(3))

stubs_basicmath.c

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


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

Makefile

.PHONY: all clean 

all: main
    ./main

main:
    gcc -c basicmath.c
    ocamlc -c stubs_basicmath.c
    ocamlopt -o main basicmath.o stubs_basicmath.c main.ml 


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

Downloads

basic-ocaml-ffi-cfile_20240829235643.zip