When you use the interface definition language to describe a C variable to the Dylan compiler, the compiler generates new Dylan getter and setter functions for reading and setting the variable's value from Dylan. If the variable is constant, it defines a getter function only.
The getter function converts the C value to a Dylan value before returning it according to the variable's declared type. Similarly, the setter function converts its argument, as Dylan value, into a C value before setting the C variable. These conversions happen according to the same rules that apply to other C-Dylan world transition points, such as argument passing or structure slot access.
In order for Dylan to be able to access a C variable correctly, we must describe the variable to Dylan in the same detail that a C header file would give to a C program that uses it. Specifically, we must provide the C name and the type of the variable. As with struct and function definitions, we indicate C types by naming the appropriate Dylan designator classes.
Here is an example of defining and using C variables. Suppose we have the following extern C variable declaration:
extern double mean;
We describe C variables to Dylan using the C-FFI macro define C-variable:
define C-variable C-mean :: <C-double> c-name: "mean"; end C-variable;
The name immediately after the define C-variable is the name of the Dylan variable to which the getter for our C variable will be bound. In this case it is C-mean.
We give the C name of the variable as the value of the keyword c-name:. Once we have compiled the definition -- and assuming the compiled version of the C library defining mean has been linked in with the Dylan application -- we can call the getter function just like any other Dylan function:
? C-mean(); 1.5
By default, the C-FFI also defines a setter function for the variable. The setter name uses Dylan's convention of appending "-setter" to the getter name.
? C-mean() := 0.0; 0.0 ? C-mean(); 0.0
As described above, when values are passed back and forth between Dylan and C, the C-FFI performs automatic conversions. In this case, the type of the variable is a fundamental numeric type which means that the C-FFI accepts and returns Dylan floats, converting to and from raw C floats as necessary.
Note: We could achieve the same result by using the define C-address macro, which defines a constant that is a pointer to the storage allocated for the C variable.