Allocating Memory with XDR
XDR routines not only do input and output, they also do memory allocation. Consider the following XDR routine, xdr_chararr1, which deals with a fixed array of bytes with length SIZE.
xdr_chararr1 (xdrsp, chararr)
XDR *xdrsp;
char chararr[];
{
char *p;
int len;
p = chararr;
len = SIZE;
return (xdr_bytes (xdrsp, &p, &len, SIZE));
}
If space has already been allocated in it, chararr can be
called from a server. For example:
char chararr [SIZE];
svc_getargs (transp, xdr_chararr1, chararr);
If you want XDR to do the allocation, you need to rewrite this
routine in the following way:
xdr_chararr2 (xdrsp, chararrp)
XDR *xdrsp;
char **chararrp;
{
int len;
len = SIZE;
return (xdr_bytes (xdrsp, charrarrp, &len, SIZE));
}
Then the RPC call might look like this:
char *arrptr;
arrptr = NULL;
svc_getargs (transp, xdr_chararr2, &arrptr);
/*
*Use the result here
*/
svc_freeargs (transp, xdr_chararr2, &arrptr);
The character array can be freed with the svc_freeargs macro. This operation does not attempt to free any memory in the variable, indicating the variable is null.
Each XDR routine is responsible for serializing, deserializing, and freeing memory. When an XDR routine is called from the callrpc routine, the serializing part is used. When an XDR routine is called from the svc_getargs routine, the deserializer is used. When an XDR routine is called from the svc_freeargs routine, the memory deallocator is used.