Search code examples
matlablinkermatlab-deploymentmatlab-compiler

Create a DLL from MATLAB


I have created a DLL in MATLAB which provides me an interface to my .m functions.

Now I would like to use it with the MCR Runtime Library. (MCR = Matlab Compiler Runtime).

I am calling this DLL from within a C routine which eventually gets compiled with GCC (MinGW) into a wrapper DLL.

Now my function gets put into two forms:

extern LIB_XYZ_C_API 
bool MW_CALL_CONV mlxGet_path(int nlhs, mxArray *plhs[], int nrhs, mxArray *prhs[]);
extern LIB_XYZ_C_API bool MW_CALL_CONV mlfGet_path(int nargout, mxArray** p);

From these I choose the latter one as the former on seems to be kind of "old-style/legacy".

I call it this way:

char get_path(LStrHandle path)
{
    char mret = init_XYZ(); // here I call mclmcrInitialize(), mclInitializeApplication(NULL, 0) etc.
    if (mret) return mret;
    mret = 2;
    // here the relevant part begins
    mxArray * mxpath = NULL; // set it to NULL and let the callee allocate it
    bool bret = mlfGet_path(1, &mxpath);
    // now I convert the mxpath to a string
    // What do I do with the mxpath afterwards?
    // I try to free it with
    mxDestroyArray(mxpath);
    return mret;
}

And here the trouble begins: mxDestroyArray() cannot be found in the linking process:

undefined reference to `mxDestroyArray'

If I manually add -llibmx to the build process, the build runs, but then libmx.dll cannot be found, as the MCR only puts $MCR\runtime\win32 into the path, but not $MCR\bin\win32 where the libmx.dll lives.

What can I do?

Do I have to choose a different "destroy" function when I use a self-compiled DLL?

Or do I have to fool around with the path? (I don't hope so...)

Besides, there are other functions which are missing, but I think this would be resolved in the same way:

mxGetNumberOfElements
mxIsDouble
mxGetPr
mxGetM
mxGetN
mxGetData
mxIsChar
mxIsCell
mxDestroyArray
mxGetCell_730
mxSetCell_730
mxGetString_730
mxCalcSingleSubscript_730
mxGetNumberOfDimensions_730
mxCreateDoubleMatrix_730
mxCreateNumericMatrix_730
mxCreateCellMatrix_730

Solution

  • I found out that it makes a big difference if the MCR is used or an installed MATLAB installation.

    1. Use -lmclmcrrt instead of -lmx and use the correct library path for the linker.
    2. Use the correct #include files in every file used in the compilation. Especially, don't inter-mix #include "matrix.h" and the header file created together with the MATLAB DLL.