MATLAB: How to use the MEX function signature in a DLL library called using loadlibrary and calllib

calllibdllloadlibraryMATLABmexshared library

I need to build a component of my statistical model using C. It will involve hundreds of functions called through Matlab. Consequently, I don't want to build a MEX interface for each such callable function. A more main-tenable approach would be to build a single Matlab specific DLL interface, which calls into the C subsystem. The functions will take and return mxArray's, rather than C-specific structures. If I have a function using a mex-type function signature in the DLL [like
void my_function(int nlhs, const mxArray* plhs[], int rhs, const mxArray* prhs[])]
it turns out that it behave exactly like a mex function, differing only in the call mechanism (using the calllib function). However, this feature isn't documented anywhere in the shared library documentation. Is this supposed to be the correct use of the mex-type input/output signature through calllib? If yes, then I can have all required functions in a single DLL, rather than having 100s of different mex files.
What other mechanisms do I have to return multiple mxArray outputs from a single DLL function called using calllib? Eg, if i have a function signature –
mxArray* process(mxArray* in1, mxArray* in2)
– called using calllib, I can send 2 inputs and get one output. In mex, returning multiple outputs is easy through the prhs[] array. How can I do the same in a calllib function?

Best Answer

Calling a function with a mex signature with calllib is supported. The example yprime.c in extern\examples\shrlib is used demonstrate this. Documentation is minimal because we have seen little demand for this and have had few questions about it.
Other options for returning multiple things from a library call are to return an mxArray containing a cell array or structure of values or to use c pointer types and a standard C style function possibly with mxArray * arguments too. Modifying mxArray * input arguments is not recommended. Remember that the the function int foo(int size, int *vec) can be called with calllib like:
[status, outvec]=calllib('lib','foo',10,1:10);
Related Question