Using the C Math Library    

Assigning Arrays to mxArray* Variables 

Under automated memory management, you can assign a value to an mxArray* variable in two different ways:

The mlfAssign() routine copies the array value from its second argument src (representing the righthand side of the assignment) to its first argument *dest (representing the lefthand side of the assignment). If src is a temporary array, mlfAssign() only copies the pointer without copying the array data. For example,

assigns the array returned by mlfCos() to Y, a pointer to an mxArray.

mlfAssign() marks the assigned array as a bound array. You are responsible for deleting the bound arrays that result from a call to mlfAssign().

Assigning a Value to an Array Destroys Its Previous Value

If you assign a value to an array variable that already has a value, mlfAssign() destroys the variable's previous value before assigning the new value. You do not need to call mxDestroyArray() before calling mlfAssign(). For example, in these two statements,

mlfAssign() destroys the contents of c (the scalar array 5) before assigning the scalar array containing 6 to c.

Exception.   Just as the MATLAB language preserves the value of an array passed as an input argument across a function call, mlfAssign() leaves an array value unchanged (does not make a copy) if the array is a bound (not temporary) input array argument on entry to the function. For example, given this function

and this call within the function

mlfAssign() modifies the value of b locally within the function. However, because b is an input argument, the call to mlfAssign() does not destroy the old value.

Assignment by Value

mlfAssign() implements assignment by value. When the array on the righthand side of the assignment (the second argument to mlfAssign()) is already bound to a variable, the array on the lefthand side receives a copy of that array. For example,

A and B point to two different arrays.

Note that the copy is actually a shared-data copy until the application requires two separate copies of the data. The MATLAB C Math Library supports full copy-on-write semantics.

Nesting Calls to Functions that Return Arrays

You can nest calls to library functions as arguments to other library functions. When you nest calls, the library deletes the array returned from the call for you. For example, when you call the library's indexing functions, you can embed the calls to mlfScalar() that define the index values.

The two calls to mlfScalar() each return a temporary array that the function mlfIndexRef() deletes just before it returns.

See Using Automated Memory Management, which explains the rules for writing functions so that they can be nested.


 Enabling Memory Management Deleting Bound Arrays