Example: Doing a Little More (MULT2)
The system function shown in the following figure does a little more than the previous one, though not by much. It expects a single argument, which must be an array. It returns a single-precision, floating-point array that contains the values from the argument multiplied by two.
Each line is numbered to make discussion easier. These numbers are not part of the actual program. Each line of this routine is discussed below:
1-2
Include the required header files.
4
Every system routine takes the same two or three arguments. argc is the number of arguments, argv is an array of arguments. This routine does not accept keywords, so argk is not present.
6
dst will become a pointer to the resulting variable's descriptor. src points at the input variable which is found in argv[0].
7
src_d and dst_d will point to the source and destination data areas.
8
n will contain the number of elements in src.
10
Assume, for now, that the input variable will serve as both the source and destination. This will only be true if the parameter is a temporary floating-point array.
11-12
Screen out any input that is not of a basic type, and only allow arrays. A better version of this routine would handle scalar input also, but we want to keep the example simple.
14
If the input is not of IDL_TYP_FLOAT, we call the IDL_CvtFlt() function to create a floating-point copy of the argument (see Converting to Specific Types for information about converting types).
Note that the routine could also be written, more efficiently, with a C switch statement which would handle each of the eight possible data types, eliminating conversion of the input parameter. This would be more in the spirit of the IDL language, where system routines work with all possible data types and sizes, but is outside the scope of this example.
17
Here, we initialize the pointers to the source and destination data areas from the array block structure pointed to by the input variable descriptor.
19-23
If the input variable is not a temporary variable, we cannot change its value and return it as the function result. Instead, we allocate a new temporary floating point array into which the result will be placed. Notice how the number of dimensions and their sizes are taken from the source variable array block. See Array Variables and Temporary Variables.
25
Loop over each element of the arrays.
26
Do the multiplication for each element.
28
Return the temporary variable containing the result.
Testing the Example
Once we have compiled the function and linked it into IDL (possibly using LINKIMAGE), we can use the built-in IDL function INDGEN to test the new function, which we name MULT2. INDGEN returns an array of values with each element set to the value of its array index. Therefore, the statement:
prints the following on the screen:
To test our new function we use INDGEN to provide an input argument:
The result, as expected, is: