Let addstr = foreign "addstr" (string returning void) Let wrefresh = foreign "wrefresh" (window returning void) Let refresh = foreign "refresh" (void returning void) Let endwin = foreign "endwin" (void returning void) Let’s begin by defining the basic values we need, starting with the WINDOW state pointer:įoreign "newwin" (int int int int returning window) The library takes care of converting OCaml function calls and arguments into the C calling convention, invoking the foreign call within the C library and finally returning the result as an OCaml value. The terminal is only updated after refresh or wrefresh are called.Ĭtypes provides an OCaml interface that lets you map these C functions to equivalent OCaml functions. The mvwaddrstr takes a window, x/y offsets, and a string and writes to the screen at that location. The initscr and newwin create WINDOW pointers for the global and subwindows, respectively. Note that there are over 200 library calls in Ncurses, so we’re only binding a select few for this example. Ncurses clients just need to store the pointer somewhere and pass it back to Ncurses library calls, which in turn dereference its contents. The WINDOW structure holds the internal library state and is considered abstract outside of Ncurses. The Ncurses functions either operate on the current pseudoterminal or on a window that has been created via newwin. Void mvwaddstr (WINDOW *, int, int, char *)
Int mvwaddch (WINDOW *, int, int, const chtype) We’ll create a binding to the Ncurses terminal toolkit, as it’s widely available on most systems and doesn’t have any complex dependencies. Let’s dive straight into a realistic example to show you how the library looks. The simplest foreign function interface in OCaml doesn’t even require you to write any C code at all! The Ctypes library lets you define the C interface in pure OCaml, and the library then takes care of loading the C symbols and invoking the foreign function call. Work through some full examples for binding a terminal interface and UNIX date/time functions Teach you how to build higher-level abstractions in OCaml from the low-level C bindings Show how to call routines in C libraries directly from your OCaml code The mechanism by which code in one programming language can invoke routines in a different programming language is called a foreign function interface.
The compiler can link with external system libraries via C code and also can produce standalone native object files that can be embedded within other non-OCaml applications. OCaml has several options available to interact with non-OCaml code. This chapter includes contributions from Jeremy Yallop.