MATLAB: MEX-based class constructors

classconstructormex

Hi, I'm wondering if it's possible to have a class constructor be fully written in MEX? My first thought was to call the "class" function via mexCallMATLAB, and returning the resulting mxArray, however, I see in the documentation [1] that "Outputs of mexCallMATLAB have temporary scope and are automatically destroyed at the end of the MEX function call", so I don't believe this works.
Any ideas?
Thanks

Best Answer

There is no API function for directly creating a "classdef" OOP object in mex like there is for numeric, struct, cell, etc variables. So you are stuck with the mexCallMATLAB route as the only way to create such an object.
Regarding the "temporary scope" comment, that is true of nearly every API function so don't worry about it. E.g., the result of mxCreateDoubleMatrix has temporary scope. The result of mxMalloc has temporary scope. Etc. The only exception I am aware of is mxArrayToString (which I believe is an oversight by TMW and should be fixed).
So go ahead and use mexCallMATLAB to create your "classdef" OOP objects. If you make it part of the plhs[] return array then it will not be garbage collected ... it will be returned just like any other variable you put in plhs[]. If you don't make it part of the plhs[] array, then of course it will be garbage collected just like every other temporary mxArray coming from an API function.
Related Question