MATLAB: Can I use MEX API in a C++ non-MEX dll with the loadlibrary command

loadlibraryMATLABmex

I would like to build a dll with mxArray API and then load this into MATLAB with the loadlibrary command.

Best Answer

You can use MEX API in your dll and then access this dll with the MATLAB loadlibrary command. Here is a C++ example:
/*MatlabGateway.cpp*/
#include "mclmcr.h"
#include "MatlabGateway.h"
extern "C"
{
void testbugfunc(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
{
// just assign a scalar return value to 9999 so we know it
// is different to the Matlab
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
double data[1] = {9999};
memcpy(mxGetPr(plhs[0]), data, sizeof(double));
}
}
The header file:
/*MatlabGateway.h*/
#ifndef __MATLABINTERFACE_H
#define __MATLABINTERFACE_H
#include "mclmcr.h"
extern "C" void testbugfunc(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[]);
#endif
Create a MatlabGateway.exports file with the following line in it:
testbugfunc
Build the DLL in MATLAB:
mbuild MatlabGateway.cpp MatlabGateway.exports
Load the resulting DLL-file using the Generic DLL interface:
loadlibrary('MatlabGateway.dll','MatlabGateway.h')
You can verify that you can use this method with:
methodsview MatlabGateway