ArrayDataRef

From X-Plane SDK
Jump to: navigation, search

This is how to write custom array dataref handlers. This example is for integer arrays. Key points:

  • The get function returns the size of the array when NULL is passed as the return data ptr.
  • The get function returns the actual number of items returned when the data ptr is not NULL.
  • Both the get and set functions are responsible for checking out-of-bounds and making sure that they don't run off the end of the array! The plugin system does not check this for you, and code calling your array may not check either.

(For example, if a user sets a generic instrument to read the 50th item in your array, and your array is only 25 items, X-Plane will not detect this - it will simply ask you for the 50th item and you must not crash.)

#define ARRAY_DIM 10
static int g_my_array[ARRAY_DIM] = { 0 };

long my_get_array(void * refcon, int * out_values, int in_offset, int in_max)
{
    int n, r;

    // If the array ptr is null, the caller just wants to know the total item count!
    if(out_values == NULL)
        return ARRAY_DIM;

    // Calculate the number of items to return.  We must limit by both the end of 
    // our array and the total number the caller asked for - whichever is less.
    r = ARRAY_DIM - in_offset;
    if(r > in_max) r = in_max;

    // Now copy the actual items from our array to the returned memory.
    for(n = 0; n < r; ++n)
        out_values[n] = g_my_array[n + in_offset];
    return r;
}

void my_set_array(void *refcon, int * in_values, int in_offset, int in_max)
{
    int n, r;

    // Calculate the number of items to copy in.  This is the lesser of the number
    // the caller writes and the end of our array.
    r = ARRAY_DIM - in_offset;
    if (r > in_max) r = in_max;

    // Copy the actual data.
    for(n = 0; n < r; ++n)
        g_my_array[n+ in_offset] = in_values[n];
}