Passing String Data
IDL represents strings internally as IDL_STRING descriptors. For more information about IDL_STRING, see IDL Internals: Variables and IDL Internals: String Processing. These descriptors are defined in the C language as:
To pass a string by reference, IDL passes the address of its IDL_STRING descriptor. To pass a string by value the string pointer (the s field of the descriptor) is passed. Programmers should be aware of the following when manipulating IDL strings:
- Called code should treat the information in the passed IDL_STRING descriptor and the string itself as read-only, and should not modify these values.
- The
slenfield contains the length of the string without including the NULL termination that is required at the end of all C strings. - The
stypefield is used internally by IDL to keep track of how the memory for the string was obtained, and should be ignored by CALL_EXTERNAL users. sis the pointer to the actual C string represented by the descriptor. If the string is NULL, IDL represents it as a NULL (0) pointer, not as a pointer to an empty null terminated string. Hence, called code that expects a string pointer should check for a NULL pointer before dereferencing it.- You must use the functions discussed in IDL Internals: String Processing to allocate the memory for an IDL_STRING. Attempting to do this directly by allocating dynamic memory and assigning it to the IDL_STRING descriptor is a common pitfall, as discussed in Common CALL_EXTERNAL Pitfalls.
Returning a String Value
When returning a string value, a function must allocate the memory used to hold it. On return, IDL will copy this string. You can use a static buffer or dynamic memory, but do not return the address of an automatic (stack-based) variable.
Note
IDL will not free dynamically-allocated memory for this use.
Example
The following routine, found in string_array.c, demonstrates how to handle string variables in external code. This routine takes a string or array of strings as input and returns a copy of the longest string that it received. It is important to note that this routine uses a static char array as its return value, which avoids the possibility of a memory leak, but which must be long enough to handle the longest string required by the application. This is implemented as a function with a natural C interface, and a second glue routine that implements the IDL portable convention, using the one with the natural interface to do the actual work: