Reputation: 571
We are using classes in MATLAB which are passed into some C Mex functions. Previously the class objects we have been passing were all the same type, so we have been able to use mxIsClass
to verify that the objects are the correct type.
We have however changed the architecture such that the objects are now derived from the original base class to allow customisation. Effectively we have something like:
handle & mixin.Heterogeneous>
BaseClass >
Class1
Class2
Because the base class uses mixin.Heterogeneous, if I pass an array like [Class1_obj Class2_obj]
, the mex function works as expected - MATLAB treats the array as an array of type BaseClass
, and mxIsClass(obj, 'BaseClass')
returns true.
The problem arises that when we pass a single object or an array of the same derived class, say [Class1_obj1 Class1_obj2]
, into the mex function. Because they are the same type, MATLAB treats the array as type Class1
, and so mxIsClass(obj, 'BaseClass')
returns false because it only considers the class of the object and not the classes it derives from.
I'm trying to figure out if there is a way to get around this problem and make sure that the mxArray*
object in the mex function is either a BaseClass
directly, or derives from it.
I've considered simply adding checks for every known derived class name, but this seems an ugly way of doing this, not least because if we add more derived classes we need to change the mex function every time.
I suppose I could use the mexCallMATLAB
function to call isa
in MATLAB which should correctly identify that it is a base class.
I wonder also if there is a way to get MATLAB to pass the object through to the Mex function treating it as a BaseClass object rather than the derived class.
Is there a standard way of acheiving this?
Upvotes: 2
Views: 143
Reputation: 571
MATLAB's built in isa
function can be used to find out if the object or object array is the correct type. The MATLAB function does look at base clases, so doing isa(Class1_obj,'BaseClass')
does return true.
I've implemented a function in the mex file that simply calls MATLAB's own isa
function to check the type. As a reference for anyone with similar issues, the following is the C function I've written for this task.
//Check the type of class object or object array using MATLAB
static bool isa(mxArray* obj, const char* type) {
//Create LHS/RHS arrays for calling MATLAB
mxArray *lhs[1];
mxArray *rhs[2];
//Return value
bool retVal;
//Populate Inputs to MATLAB isa
rhs[0] = obj;
rhs[1] = mxCreateString(type);
//Call the MATLAB isa function
mexCallMATLAB(1, lhs, 2, rhs, "isa");
//Extract result
retVal = mxIsLogicalScalarTrue(lhs[0]);
//Cleanup
mxDestroyArray(rhs[1]);
mxDestroyArray(lhs[0]);
//Done
return retVal;
}
Upvotes: 3