Click here to Skip to main content
15,918,889 members
Articles / Programming Languages / C++
Article

MATLAB Shared Library

Rate me:
Please Sign up or sign in to vote.
4.61/5 (23 votes)
30 Dec 20032 min read 595.5K   4K   54   159
Using MATLAB compiler to build a shared library (DLL) from m-File.

Sample screenshot - Matlab Shared Library

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:

  1. 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
  2. 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;
    }
  3. 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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
CEO Solaris Electronics LLC
United Arab Emirates United Arab Emirates
I was born in Shiraz, a very beautiful famous city in Iran. I started programming when I was 12 years old with GWBASIC. Since now, I worked with various programming languages from Basic, Foxpro, C/C++, Visual Basic, Pascal to MATLAB and now Visual C++.
I graduated from Iran University of Science & Technology in Communication Eng., and now work as a system programmer for a telecommunication industry.
I wrote several programs and drivers for Synthesizers, Power Amplifiers, GPIB, GPS devices, Radio cards, Data Acquisition cards and so many related devices.
I'm author of several books like Learning C (primary and advanced), Learning Visual Basic, API application for VB, Teach Yourself Object Oriented Programming (OOP) and etc.
I'm winner of January, May, August 2003 and April 2005 best article of month competition, my articles are:


You can see list of my articles, by clicking here


Comments and Discussions

 
QuestionTo access a Matlab code in my C program Pin
Sindhu Krishnana E P10-May-07 21:25
Sindhu Krishnana E P10-May-07 21:25 
GeneralUsing M-files within C++ code Pin
xxpatanaxx8-May-07 11:39
xxpatanaxx8-May-07 11:39 
Generalerror compile Pin
mehdiing5-May-07 7:56
mehdiing5-May-07 7:56 
GeneralRe: error compile Pin
Abbas_Riazi6-May-07 2:24
professionalAbbas_Riazi6-May-07 2:24 
GeneralRe: error compile Pin
kumar Shwetaketu20-May-07 1:57
kumar Shwetaketu20-May-07 1:57 
QuestionEAccess Violation with mxCreate* Pin
NowC4-May-07 12:31
NowC4-May-07 12:31 
Questioni want to import a C code in matlab what i should do Pin
faizi ji3-May-07 20:00
faizi ji3-May-07 20:00 
AnswerRe: i want to import a C code in matlab what i should do Pin
Sindhu Krishnana E P10-May-07 21:07
Sindhu Krishnana E P10-May-07 21:07 
you can call a c function in your matlab code by converting your c code to a mex function.
for that u have to include a gateway function like as shown below. If u have a matlab installed then the help document will give you all the reqired help



Let’s look at a simple example of C code and its MEX-file equivalent. Here is a C computational function that takes a scalar and doubles it.
#include<stdio.h>
#include <math.h>
void timestwo(double y[], double x[])
{
y[0] = 2.0*x[0];
return;
}
Below is the same function written in the MEX-file format.


include ur c header files<br />
#include "mex.h"<br />
void timestwo(double y[], double x[])<br />
{<br />
y[0] = 2.0*x[0];<br />
}<br />
// This is the Gateway function<br />
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,<br />
const mxArray *prhs[])<br />
{<br />
double *x, *y;<br />
int mrows, ncols;<br />
/* Check for proper number of arguments. */<br />
if (nrhs != 1) {<br />
mexErrMsgTxt("One input required.");<br />
} else if (nlhs > 1) {<br />
mexErrMsgTxt("Too many output arguments");<br />
}<br />
/* The input must be a noncomplex scalar double.*/<br />
mrows = mxGetM(prhs[0]);<br />
ncols = mxGetN(prhs[0]);<br />
if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) ||<br />
!(mrows == 1 && ncols == 1)) {<br />
mexErrMsgTxt("Input must be a noncomplex scalar double.");<br />
}<br />
/* Create matrix for the return argument. */<br />
plhs[0] = mxCreateDoubleMatrix(mrows,ncols, mxREAL);<br />
/* Assign pointers to each input and output. */<br />
x = mxGetPr(prhs[0]);<br />
y = mxGetPr(plhs[0]);<br />
/* Call the timestwo subroutine. */<br />
timestwo(y,x);<br />
}<code><br />
<br />
save this code as a .c function(programname.c)<br />
go to the matlab command window<br />
if you are doing the mex function for the first time you have to do a mex setup<br />
<br />
the following are the steps to do that<br />
This example shows the process of setting your default compiler to the<br />
Microsoft Visual C++ Version 6.0 compiler.<br />
mex -setup(type in command window)<br />
Please choose your compiler for building external interface (MEX)<br />
files.<br />
Would you like mex to locate installed compilers [y]/n? n<br />
Select a compiler:<br />
[1] Compaq Visual Fortran version 6.6<br />
[2] Lcc C version 2.4<br />
[3] Microsoft Visual C/C++ version 6.0<br />
[0] None<br />
Compiler: 3<br />
Your machine has a Microsoft Visual C/C++ compiler located at<br />
D:\Applications\Microsoft Visual Studio. Do you want to use this<br />
compiler [y]/n? y<br />
Please verify your choices:<br />
Compiler: Microsoft Visual C/C++ 6.0<br />
Location: C:\Program Files\Microsoft Visual Studio<br />
Are these correct?([y]/n): y<br />
The default options file:<br />
"C:\WINNT\Profiles\username\ApplicationData\MathWorks\MATLAB\R13<br />
\mexopts.bat" is being updated from ...<br />
Building MEX-Files<br />
<br />
If the specified compiler cannot be located, you are given the message:<br />
The default location for compiler-name is directory-name,<br />
but that directory does not exist on this machine.<br />
Use directory-name anyway [y]/n?<br />
Using the setup option sets your default compiler so that the new compiler is<br />
used every time you use the mex script.<br />
<br />
Once you have chosen you compiler build ur program by typing<br />
mex programname.c<br />
then you can check your program by typing "programname(2)" in command window<br />
or you can create an m file to call this program<br />
%mfile<br />
x=2;<br />
y=programname(x);<br />
disp(y)<br />
%mfile ends<br />
<br />
check it out

QuestionHow ca I do the download of the MatlabSharedLib_demo.zip? Pin
giovanitonel24-Nov-06 0:37
giovanitonel24-Nov-06 0:37 
AnswerRe: How ca I do the download of the MatlabSharedLib_demo.zip? Pin
Abbas_Riazi24-Nov-06 0:45
professionalAbbas_Riazi24-Nov-06 0:45 
QuestionHow to access MATLAB functions in C# Pin
Shakeel Mumtaz28-Oct-06 19:05
Shakeel Mumtaz28-Oct-06 19:05 
AnswerRe: How to access MATLAB functions in C# Pin
Sindhu Krishnana E P10-May-07 3:09
Sindhu Krishnana E P10-May-07 3:09 
GeneralRe: How to access MATLAB functions in C# Pin
Shakeel Mumtaz11-May-07 7:16
Shakeel Mumtaz11-May-07 7:16 
QuestionRe: How to access MATLAB functions in C# Pin
kumar dhruva 15-Jun-11 23:48
kumar dhruva 15-Jun-11 23:48 
GeneralMCC: Compiling a Matlab function that gets integer arguments Pin
amitkagian16-Oct-06 6:00
amitkagian16-Oct-06 6:00 
QuestionCompatibility between a Matlab dll and Delphi Pin
PititeBato11-Oct-06 22:39
PititeBato11-Oct-06 22:39 
AnswerRe: Compatibility between a Matlab dll and Delphi Pin
ElvedinHamzagic21-Oct-07 3:52
ElvedinHamzagic21-Oct-07 3:52 
QuestionCalling MatLab DLL from VB6 "Can't find DLL entry point..." error Pin
icesktr122-Aug-06 7:53
icesktr122-Aug-06 7:53 
AnswerRe: Calling MatLab DLL from VB6 "Can't find DLL entry point..." error Pin
Kashif Ishaq13-Sep-07 20:05
Kashif Ishaq13-Sep-07 20:05 
Generalusing dll c++ through matlab Pin
gariani19-Jun-06 23:53
gariani19-Jun-06 23:53 
QuestionI cant merge the DLL with the C++ Pin
schone24-May-06 6:17
schone24-May-06 6:17 
GeneralMCC!!!!!???????????????????!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Pin
lamionne18-Mar-06 1:56
lamionne18-Mar-06 1:56 
GeneralRe: MCC!!!!!???????????????????!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Pin
kumar Shwetaketu21-May-07 18:58
kumar Shwetaketu21-May-07 18:58 
Generalplease help me Pin
lamionne18-Mar-06 1:42
lamionne18-Mar-06 1:42 
Generalstudent needsc help in matlab mcc Pin
lamionne15-Mar-06 23:22
lamionne15-Mar-06 23:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.