Lifetime Management of C++ Objects in MATLAB

If a library creates an object,​ then the library is responsible for releasing the memory. Likewise, if MATLAB® creates the object,​ then MATLAB is responsible for releasing the memory. There are situations, however, where memory allocated by both the user library and MATLAB might be combined into a single MATLAB object. MATLAB lets you control the lifetime management of objects by specifying 'ReleaseOnCall' and 'DeleteFcn' arguments in the library definition file.

Pass Ownership of Memory to the Library

MATLAB owns memory that is allocated by calling a constructor. The user library should not free this memory. To change this behavior, set the 'ReleaseOnCall' argument in defineArgument (FunctionDefinition) or defineArgument (MethodDefinition).

Suppose that you have a function in library libname which takes ownership of the input argument.

void setInputObj(ObjClass *obj);

If you create the argument in MATLAB, then MATLAB owns the memory.

obj = clib.libname.ObjClass;

If you pass obj to setInputObj, then both MATLAB and setInputObj own the memory, which is unsafe.

clib.libname.setInputObj(obj)

To transfer memory ownership to the library, modify the setInputObj definition in the library definition file.

%setInputObjDefinition = addFunction(libnameDefinition, ...
%    'setInputObj(ObjClass * obj)', ...
%defineArgument(setInputObjDefinition,'obj','clib.libname.ObjClass',<DIRECTION>,<SHAPE>);

Set DIRECTION and SHAPE and add a 'ReleaseOnCall' argument.

defineArgument(setInputObjDefinition,'obj','clib.libname.ObjClass','input',1,'ReleaseOnCall',true);

Pass Ownership of Memory to MATLAB

MATLAB does not free memory allocated by the library. If a function returns a pointer or a reference to an object, you can transfer ownership of the memory to MATLAB using the 'DeleteFcn' argument in the defineOutput (FunctionDefinition) or defineOutput (MethodDefinition) functions.

If you specify a library function for the deleter function, then that function is not included in the interface and users cannot call the function from MATLAB. The MATLAB user calls the MATLAB delete function, which calls the function specified by deleteFcn.

Suppose that you have a member function objFree that frees memory.

ObjClass *objCreate(int32 a, int32 b); 
void objFree(ObjClass *obj);

To use objFree when MATLAB deletes the object, modify the objCreate definition in the library definition file.

%defineOutput(objCreateDefinition,'RetVal','clib.lbiname.ObjClass,<SHAPE>);

Set SHAPE and add a 'DeleteFcn' argument.

defineOutput(objCreateDefinition,'RetVal','clib.libname.ObjClass,1,'DeleteFcn','libname::objFree');

The MATLAB delete function calls libname::objFree.

myObj = clib.libname.objCreate(x,y)
delete(myObj);

See Also

| | |