Loading Blog Search...

Thursday, October 28, 2004

How to call ocaml functions from C.

Here is an example of how to invoke a ocaml function from c codes.
/* str.c --- readin a string and format it as italy */
#include <stdio.h>
#include <caml/mlvalues.h>
#include <caml/callback.h>
int main (int argc,char **argv)
{
   caml_main(argv);
   if (argc>1)
     printf( callback(*caml_named_value("format string"),copy_string(argv[1])));
   return 0;
}

(* forstr.ml *)
let format_str (w:string) =
  "<i>"^w^"</i>";;
Callback.register "format string" format_str;;

to compile as native format:
1. ocamlopt -output-obj forstr.ml -o forstring.o
2. gcc -c str.c  /* cannot use g++ */
3. gcc -o test forstring.o str.o -L/usr/lib/ocaml/3.08/ -lasmrun -ldl -lm

No comments: