Introduction
Some times it is required that we build a shared library (DLL) from an m-file. M-files are functions that are written in Matlab editor and can be used from Matlab command prompt. In m-files, we employ Matlab built-in functions or toolbox functions to compute something. In my past articles, I showed you some ways to use Matlab engine (vis. API, C++ class or Matlab engine API) for employing Matlab built-in functions, but what about functions that we develop? How can we use them in VC? Is there any interface? This article shows you an idea to employ your own Matlab functions.
Shared Libraries
Shared libraries or DLLs are files that export some functions. We can use exported functions in any language. Here is a brief instruction to build shared libraries from Matlab m-files:
- Compile your m-file into a DLL (from Matlab command prompt):
mcc -t -L C -W lib:mylib -T link:lib -h <M-file> libmmfile.mlib
The -t option tells the Matlab compiler to translate the m-file to the target language. The -L option specifies the target language, which is chosen to be C. The -W option tells the Matlab compiler to build a wrapper for the library with the name specified by "lib:". The -T option tells the compiler what stage should be reached and for what intentions. Here we link our application together to build a shared library (DLL). Specifying libmmfile.mlib tells Matlab compiler to link against Matlab m-file math routine.
This step will produce mylib.dll, mylib.lib and mylib.h. For debugging purposes, you can add the -g switch to produce a DLL suitable for debugging in MSVC.
For example, I wrote my own mean function and saved it as MeanFunction.m:
function y=MeanFunction(x)
[m,n]=size(x);
k=0;
for i=1:n
k=k+x(i);
end
y=k/n;
and compiled it with mcc:
mcc -t -L C -W lib:MeanFunctionLib -T link:lib MeanFunction.m libmmfile.mlib
- Create your project in VC. In your main CPP file, include your function header file and add the related library. Here I create a simple console application. Make sure to call initialization and termination routines from your code before and after of calling the m-file function.
#include "stdafx.h"
#include "matlab.h"
#include "MeanFunctionLib.h"
#pragma comment(lib, "libmx.lib")
#pragma comment(lib, "libmatlb.lib")
#pragma comment(lib, "libmat.lib")
#pragma comment(lib, "libmmfile.lib")
#pragma comment(lib, "MeanFunctionLib.lib")
int main(int argc, char* argv[])
{
mxArray* result;
mxArray* x;
double myArray[5]={10.2, 3, 6.3, 5.4, 5.9};
x=mxCreateDoubleMatrix(1, 5, mxREAL);
memcpy(mxGetPr(x), myArray, 5 * sizeof(double));
MeanFunctionLibInitialize();
result=mlfMeanfunction(x);
MeanFunctionLibTerminate();
mlfPrintMatrix(result);
mxDestroyArray(x);
mxDestroyArray(result);
return 0;
}
- Build your project.
Notice that you must use Matlab C API or Matlab C++ class library to use mxArray
or mwArray
. For more information, refer to my articles:
Enjoy!