ONC+ Developer's Guide


In the C language, a string is defined as a sequence of bytes terminated by a null byte, which is not considered when calculating string length. However, when a string is passed or manipulated, a pointer to it is employed. Therefore, the XDR library defines a string to be a char *, and not a sequence of characters. The external representation of a string is drastically different from its internal representation.

Externally, strings are represented as sequences of ASCII characters. Internally, strings are represented with character pointers. Conversion between the two representations is accomplished with the routine xdr_string():

bool_t xdr_string(xdrs, sp, maxlength)
   XDR *xdrs;
   char **sp;
   u_int maxlength;

The first parameter xdrs is the XDR stream handle. The second parameter sp is a pointer to a string (type char **). The third parameter maxlength specifies the maximum number of bytes allowed during encoding or decoding. Its value is usually specified by a protocol. For example, a protocol specification might say that a file name can be no longer than 255 characters. The routine returns FALSE if the number of characters exceeds maxlength, and TRUE if it doesn't.

The behavior of xdr_string() is similar to the behavior of other routines discussed in this section. For example, in the direction XDR_ENCODE, the parameter sp points to a string of a certain length. If the string does not exceed maxlength, the bytes are serialized.

The effect of deserializing a string is subtle. First the length of the incoming string is determined; it must not exceed maxlength. Next sp is dereferenced. If the value is NULL, a string of the appropriate length is allocated and *sp is set to this string. If the original value of *sp is nonnull, the XDR package assumes that a target area has been allocated that can hold strings no longer than maxlength. In either case, the string is decoded into the target area. The routine then appends a null character to the string.

In the XDR_FREE operation the string is obtained by dereferencing sp. If the string is not NULL, it is freed and *sp is set to NULL. In this operation xdr_string() ignores the maxlength parameter.

Note that you can use XDR on an empty string ("") but not on a NULL string.