X
4276

Passing Multidimensional arrays to C with CALL_EXTERNAL

In IDL the CALL_EXTERNAL function is often used to call an external C routine. When passing an array from IDL to C through CALL_EXTERNAL, IDL passes the address of the array's first element. The address is recieved in the C routine as a void pointer, which can easily be cast to the appropriate type. Thus within C the programmer has complete access to the address space of the original IDL array.

It is often the case, though, that the user requires the array in C to be multidimensional, so that its elements can be accessed though standard index notation (ie arr[1][3][0]). This is true for typical mathematical calculations whose formulas look horrible for arrays interpreted as one dimension. In that case it is not possible to simply declare the array in the same address space. That is:

    float arr[10][10][10] = (float *)argv[0]; //INCORRECT!!

C programmers call arr a "non-modifiable l-value", so even though arr itself is a pointer, it cannot appear on the left hand side on an assignment operator.

Include below is a description of a simple way to solve this problem.Discussion:
Explicitly cast the void pointer to a pointer to an array as follows:

    float (*arr)[nx][ny][nz] = (float *)argv[0];

and then, for example, the array elements can be referenced as:

    (*arr)[1][3][1]

See the example code below for a detailed, working example, which includes the C routine, the IDL calling routine, and the compiler and linker flags used on the system on which it was tested (Linux).

/* C routine to return an array element */

   /* test.c */
   int test(int argc,void **argv)
   {
    int (*parray)[7][6][5]= argv[0];
    return( (*parray)[1][1][4]);
   }

;compile and link statement on Linux

   gcc -shared -o test.so test.c
;IDL Version 5.6 (linux x86 m32). (c) 2002, Research Systems, Inc.
;
IDL> arr=lonarr(5,6,7)
IDL> arr[4,1,1]=121
IDL> print, call_external('test.so','test',arr)
121