User`s guide

7 Libraries
Note that in both cases, the g enerated functions allocate memory for their
return values. If you do not delete this memory (via
mxDestroyArray)when
you are done with the output variables, your program will leak memory.
Yo ur program may call whichever of these functions is more convenient, as
they both invoke your M-file function in an identical fashion. M ost programs
will likely call the
mlf form of the function to avoid managing the extra
arrays required by the
mlx form. The example program in triangle.c calls
mlfSierpinski.
mlfSierpinski(2, &x, &y, iterations, dra w);
In this call, the caller requ ests two output arguments, x and y, and provides
two inputs,
iterations and draw.
If the o utput variables you pass in to an
mlf function are not NULL, the mlf
function will attempt to free them using mxDestroyArray.Thismeansthat
you can reuse output variables in consecutive calls to
mlf functions without
worrying about memory leaks. It also implies that you must pass either
NULL
or a valid MATLAB array for all output variables or your program will fail
because the memory manager cannot distinguish between a noninitialized
(invalid) a rray pointer and a valid a rray. It will try to free a pointer that is
not NULL -- freeing an invalid pointer usually causes a segmentation fault
or similar fatal error.
UsingvararginandvarargoutinanM-FunctionInterface
If your M-function interface uses varargin or varargout, you must pass
them as cell arrays. For example, if you have
N varargins, you need to create
one cell array of size
1-by-N. Similarly, varargo uts are returned back as
one cell array. The length of the
varargout is equal to the number of return
values specified in the function call minus the number of actual variables
passed. As in M ATLAB, the cell array representing
varagout hastobethe
last return variable (the variable preceding the first input variable) and the
cell array representing
varargins has to be the last formal parameter to
the function call.
For information on creating cell a rrays, refer to the C-Mex function interface
in the External Interfaces documentation.
7-30