Ch.9 SML# feature: direct interface to C

§ 9.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 "symbol" : type

symbol 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 the named function and bind the SML# variable id to that function. A target function linked by this declaration can be any code as far as it is in a standard calling convention of the OS in which SML# runs. The linking to the function is performed at linking time. So, to produce an executable file of SML# program containing this _import declaration, it is required to specify either a library or an object file to the command line of SML# command to link it with the SML# program. Some of standard C libraries (including libc and libm in Unix family OS) are linked 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.

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."];
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”.