Ch.6 SML# feature: direct interface to C

§ 6.1. Declaring and using C functions

In order to use C function, you only have to declare it in SML# in the following syntax.

val id = _import string : type

string is the name of the C function. type is its type. Next section explain how to write the type of a C function.

This declaration instructs SML# compiler to link an object file containing the named function and bind the SML# variable id to that function. An object file can be any file as far as it is in a standard format of the OS in which SML# runs. It can be a stand alone fine (???.o file in a Unix family OS) or a shared library (???.so file in a Unix family OS). SML# compiler searches for the named function in the set of object files that are (explicitly or implicitly given) and link the appropriate file to make an executable file. Some of standard C libraries (including libc and libm in Unix family OS) are search by default.

This declaration can appear whenever val declaration is allied. After this declaration, variable id can be used as an ordinary variable defined in SML#.

As an example, consider the standard C library function.

extern int puts (char *);

This function takes a string, appends a newline code and outputs it to the standard output, and returns the number of characters actually printed. If printing fails, then it returns the integer representing EOF (which is -1 in Linux). This function can be used by writing the following declarations.

val puts = _import "puts" : string -> int

As seen in this example, C function can bound and used just by writing _import keyword followed by the name and the type of the desired function. The following is interactive session using puts.

# val puts = _import "puts" : string -> int;
val puts = _ : string -> int
# puts "My first call to a C library";
My first call to a C library
val it = 29 : int
map puts ["I","became","fully","operational","in","April","6th","2012."];
I
became
fully
operational
in
April
2nd
2012.
val it = [2, 7, 6, 12, 3, 6, 4, 5] : int list

The imported C functions can be freely used according to the ML's programming principle – “expressions are freely composed as far as they are type consistent”.