cocamlinterfacing

OCaml - Compile OCaml and C code that uses Ctypes


I'm trying to learn how to call routines in C directly from OCaml code, using the Ctypes library.

I have this basic example with two files: hello.ml and hello.c.

hello.ml looks like this:

open Ctypes
open Foreign

let hello = 
    foreign "hello" (float @ -> returning void)
;;

let () = 
    hello 3.15
;;

hello.c looks like this:

#include <stdio.h>

void hello(double x)
{
    if ( x > 0)
        printf("hello!\n");
}

How do I compile these two files into one executable?

The process of manually compiling/linking code is scary to me and I don't understand it very well. I usually use a Makefile template to compile my code because that's really easy.


Solution

  • Here's an example that I use on OS X.

    in simple.c

    int adder(int a, int b)
    {
        return a + b;
    }
    

    and in simple.ml

    open Ctypes
    open Foreign
    let adder_ = foreign
        "adder" (int @-> int @-> returning int)
    
    let () =
      print_endline (string_of_int (adder_ 1 2))
    

    Then I do

    clang -shared simple.c -o simple.so 
    ocamlfind ocamlopt -package ctypes.foreign -cclib simple.so -linkpkg simple.ml -o Test
    ./Test
    

    And that should print out 3 on the terminal.