Ch.6 SML# feature: direct interface to C

§ 6.2. Declaring types of C functions

C functions that can be imported to SML# are those whose types are representable in SML#. The type in _import declaration is the type of C function written in SML# notation. SML# compiler generates a small piece of code to set up parameters according to the type specification and to call the function, and binds the variable to the code. The bound variable can then be used as a function the corresponding SML# type determined by the compiler.

The table 6.1 shows the C types representable in SML# and the corresponding SML# types.

C type SML# notation corresponding SML# type restriction (note)
int int int
char char char
unsigined int word word
float float float
double real real
const char * string string export only
constτ * τ vector τ vector if element types are representable
τ * τ array τ array if element types are representable
pointer to a struct record type record type if element types are representable
τ0 id(τ1,,τn) (τ1,,τn) -> τ0 τ1 * * τn -> τ0 if element types are representable
void* unit ptr _ (C pointer type )

Figure 6.1. CとSML#の型の対応

As show in this table, most of C types directly corresponds to SML# types.

The following shows some simple examples.

# val sin = _import "sin" : real -> real
val sin = _ : real -> real
# sin (Math.pi / 6.0); val it = 0.5 : real

As we shall explain in the next section, functions taking multiple parameters and structs can also be imported.