How do I integrate my C++ shared Library generated from MATLAB R2013b in Visual Studio 2013?
MATLAB: How to integrate the C++ shared Library generated from MATLAB R2013b in Visual Studio 2013
MATLABMATLAB Compiler SDK
Related Solutions
The steps to create a C shared library from within MATLAB are:
1. Select the compiler to be used by MCC:
mbuild -setup
2. Compile your MATLAB files into a DLL (on Windows):
mcc -B csharedlib:mylib <MATLAB files>
The -B csharedlib option is a bundle option that expands into
-W lib:<libname> -T link:lib
The -W lib:<libname> option tells the MATLAB Compiler to generate a function wrapper for a shared library and call it libname. The -T link:lib option specifies the target output as a shared library.
Note the directory where the Compiler puts the shared library because you will need it later on. This step will produce mylib.dll, mylib.lib, and mylib.h. You can add the -g option to produce a DLL suitable for debugging in MSVC (or your own IDE).
Alternatively, you may also use DEPLOYTOOL and choose C Shared library as the target to achieve this.
3. Add mylib.lib to your MSVC (or your own IDE) project.
4. Make sure to call the initialization and termination routines from your code before calling any of the exported DLL functions.
To initialize the shared library and the MCR, you need to call:
mclInitializeApplication(NULL,0);mylibInitialize();
Afterwards, you should call the termination routine:
mclTerminateApplication();mylibTerminate();
5. You can call the functions compiled from the MATLAB code by invoking the exported DLL functions from your C code. For example:
Example:
In MATLAB:
1. Write a MATLAB function named foo and save it as foo.m with the following code:
function y = foo(x)y = x+1;
2. Select the compiler to be used by MCC:
mbuild -setup
3. Use the MATLAB Compiler to compile foo.m into C code that can be included in a C shared library:
mcc -B csharedlib:foolib foo.m
This will generate the following files:
foolib.ctf
foolib.h
foolib.dll
foolib.lib
foolib.exp
foolib_mcc_component_data.c
foolib.c
foolib.exports
In Microsoft Visual 2010 Express Edition
1. Start the Microsoft Visual 2010 Express Edition IDE.
2. Go to FILE and NEW. In the Project Types field, select Visual C++ Projects. In the Templates field, select Win32 Console Project. In the Name field type "test". Click OK. In the Win32 application Wizard, select Application Settings. Under Additional Options, check Empty project. Click Finish.
3. Select the Solution Explorer tab. Select Source Files, select Project menu option, select Add New Item. In the Templates tab select C++ Source file, type "foowrap.c" in the File name field and click Open.
4. Enter the following code in the foowrap.c file:
/* Include the MCR header file and the library specific header file* as generated by MATLAB Compiler */#include "mclmcr.h" #include "foolib.h"#include <stdio.h>int main(){mxArray *x_ptr;mxArray *y_ptr=NULL;double *y;double ret;/* Call the MCR and library initialization functions */if( !mclInitializeApplication(NULL,0) ){fprintf(stderr, "Could not initialize the application.\n");exit(1);}if (!foolibInitialize()){fprintf(stderr,"Could not initialize the library.\n");exit(1);}/* Create an mxArray to input into mlfFoo */x_ptr = mxCreateDoubleScalar(1);/* Call the implementation function *//* Note the second input argument should be &y_ptr instead of y_ptr*/mlfFoo(1,&y_ptr,x_ptr);/* The return value from mlfFoo is an mxArray so we must extract the data from it */y = mxGetPr(y_ptr);ret = *y;/* Print a double precision number*/printf("The output of foo is %f\n",ret);/* Call the library termination function */foolibTerminate();mxDestroyArray(x_ptr);mxDestroyArray(y_ptr);mclTerminateApplication();return 0;}
5. Select your project in the Solution Explorer. From Project menu option, select Properties. Open the Linker folder and select the General category. Add the location of foolib.lib and the following
$MATLABROOT\extern\lib\<arch>\microsoft\msvc71
in the Additional Library Directories field. Note $MATLABROOT is the MATLAB root directory on your machine, as returned by typing
matlabroot
at the MATLAB Command Prompt.
For example, you may have
c:\foo;$MATLABROOT\extern\lib\<arch>\microsoft\msvc71
in the Additional Library Directories field.
Note that for MATLAB releases starting with MATLAB 7.2 (R2006a), there are no subfolders under
$MATLABROOT\extern\lib\<arch>\microsoft
Therefore add this folder instead of
$MATLABROOT\extern\lib\<arch>\microsoft\msvc71
if you are using MATLAB 7.2 or later.
6.After specifying the library directories, select the Input category and type the following libraries in the Additional Dependencies field:
mclmcrrt.lib
foolib.lib
7. Open C/C++ folder, select General. Add to Additional Include directories field:
$MATLABROOT\extern\include
Also add to the Additional Include directories field the directory in which foolib.h is located.
8.Under C/C++ folder, select Code Generation. In the Runtime Library, select Multi-threaded DLL. Click OK.
9. Check the target machine flag in Visual Studio: This should correspond to the libraries that you are linking against. For example, if you specify ’x64’, it should link against the 64-bit MATLAB libraries. If you specify 'Win32', it should link against 32-bit MATLAB libraries.
For additional information on how the target platform of the Visual Studio project can be changed, refer to
"How to: Configure Visual C++ Projects to Target 64-Bit Platforms" at:
<http://msdn2.microsoft.com/en-us/library/9yb4317s(VS.80).aspx>
10. Go to Build->Build Solution. You should now have built test.exe.
Please make sure to choose 'x64' option from the drop down menu for the 'Solution Platform' window in Visual Studio before building your project if you are linking against '64 bit' libraries.After building the project, an additional folder named 'x64' will be created in your current project working directory and your executable will be placed in it.
11. Place foolib.dll in folder where test.exe is located, if you have changed the Visual Studio Platform to 64bit then your executable will be in a folder 'x64'.
12. Run your application.
NOTE: The <arch> folder mentioned above referred to "win32" or "win64" folder depending on whether you want to create a 32 bit or 64 bit C shared library respectively.
This solution explains how to generate a C shared library with the MATLAB Compiler and call it from a Windows Forms Application in Microsoft Visual Studio (MSVS) 2005. This example was written using MATLAB Compiler 4.4 (R2006a). However, the steps should be very similar for MATLAB Compiler 4.0 (R14) and later versions.
The following steps summarize the process of creating a C shared library and calling it from a Windows Forms Application.
1. In MATLAB, select a compiler with the MBUILD command.
mbuild -setup
2. Compile your MATLAB files into a C shared library with the MCC command.
mcc -B csharedlib:mylib <MATLAB files>
The -B csharedlib option is a bundle option that expands into -W lib:<libname> -T link:lib. The -W lib:<libname> option tells MATLAB Compiler to generate a function wrapper for a shared library and call it libname. The -T link:lib option specifies the target output as a shared library.
3. Add the MCR library, your library, the library path and the include directories to your MSVS project. Copy the MATLAB generated CTF- and DLL-files to your project directory.
4. Call the MCR (MATLAB Compiler Runtime) and library initialization and termination routines from your project code. To initialize the shared library and the MCR, call:
mclInitializeApplication(NULL,0);mylibInitialize();
After all the calls to your shared library functions, call:
mclTerminateApplication();mylibTerminate();
5. Build and run your project in MSVS.
The following detailed steps create an example C shared library that is called from a Microsoft Visual Studio 2005 project.
1. Save the following MATLAB code to a file called "foo.m":
function y = foo(x)y = x*10;
2. Execute the MBUILD command at the MATLAB prompt:
mbuild -setup
The version number of the Microsoft Visual Studio 2005 C/C++ Compiler is 8.0. Select this compiler.
3. Generate a C shared library from foo.m with the MCC command:
mcc -B csharedlib:foolib foo.m
This will generate the following files:
foolib.ctf foolib.h foolib.dll foolib.lib foolib.exp foolib_mcc_component_data.c foolib.c foolib.exports
Note your current directory where these files are placed, as you will need it later on. You can specify the directory where the files will be placed by using the -d option with MCC. For more information about available options for the MCC command, enter the following command at the MATLAB prompt:
doc mcc
4. In Microsoft Visual Studio 2005, go to File->New Project. In the Project Types field, select Visual C++. In the Templates field, select Windows Forms Application. In the Name field type "test". Click OK.
5. In the Form that is automatically created, add 2 text boxes and a push button. Change the name of one of the text boxes to "inBox" and the other to "outBox". This can be done by right-clicking on the text box and selecting Properties. Edit the Name property to the appropriate value. You do not need to change the name of the push button.
6. Double click on the push button. This will bring you to the Click function for this button. Paste the following code into that function:
double input = System::Double::Parse(inBox->Text); mxArray *x_ptr; mxArray *y_ptr=NULL; double *y; // Create an mxArray to input into mlfFoo x_ptr = mxCreateDoubleScalar(input); // Call the implementation function // Note the second input argument should be &y_ptr instead of y_ptr. mlfFoo(1,&y_ptr,x_ptr); // The return value from mlfFoo is an mxArray. // Use mxGetpr to get a pointer to data it contains. y = (double*)mxGetPr(y_ptr); // display the result in the form outBox->Text = ""+*y; //clean up memory mxDestroyArray(x_ptr); mxDestroyArray(y_ptr);
7. Open the test.cpp source file. Add the library header import statement
#include "foolib.h"
before the Form header input statement
#include "Form1.h"
8. Locate the main function in the test.cpp file. Add the MCR and library initialization function calls before the Form is opened. To do this, paste this code
/* Call the MCR and library initialization functions */ if( !mclInitializeApplication(NULL,0) ) { MessageBox::Show("Could not initialize the application."); exit(1); } if (!foolibInitialize()) { MessageBox::Show("Could not initialize the library."); exit(1); }
just before the line
Application::Run(gcnew Form1());
9. Add the library and MCR terminate function calls after the call to open the form, but before the return statement. To do this, paste this code
/* Call the MCR and library termination functions */ foolibTerminate(); mclTerminateApplication();
just after the line
Application::Run(gcnew Form1());
10. Select your project in the Solution Explorer. Select Project -> Properties. Under Configuration Properties->General, change "Common Language Runtime support" from "Pure MSIL Common Lanaguage Runtime Support (/clr:pure)" to "Common Lanaguage Runtime Support (/clr)". Click OK.
11. Under Configuration Properties->Linker->General category select the Additional Library Directories field. Add the location of foolib.lib, and the following directory:
$MATLAB\extern\lib\win32\microsoft
Note that $MATLAB should be replaced with the MATLAB installation directory, as returned by typing
matlabroot
at the MATLAB command prompt.
12. Under Configuration Properties->Linker->Input category add the following libraries in the Additional Dependencies field:
mclmcrrt.lib foolib.lib
13. Under Configuration Properties->C/C++ category->General select the Additional Include Directories field. Add the location of foolib.lib, and the following directory:
$MATLAB\extern\include
replacing $MATLAB with the MATLAB installation directory as above.
14. Also under the C/C++ category, select Code Generation. In the Runtime Library, select Multi-threaded DLL. Click OK to close the Properties window.
15. Go to Build->Build Solution. You should now have built test.exe.
16. Place foolib.dll and foolib.ctf in folder where test.exe is located.
If you are using MATLAB 7.3 (R2006a) and you want to run the application from within MSVS, you will also need to change the debug working directory to ensure that the CTF-file is found. To do this select Project -> Properties. Under Configuration Properties->Debugging in the Working Directory field, enter the name of the directory where the DLL- and CTF-files are located. For example if they are in the Debug subdirectory of your project, simply enter the text "Debug".
17. Run your application.
You can download the example MSVS project used for this solution and the associated files from the link below. You will still need to compile the MATLAB file (step 1-3), update the include and library directories (steps 11 and 12), build the application (step 15), and copy the DLL and CTF files to the appropriate folder (step 16).
Note:
A. MathWorks does not provide technical support for using Microsoft Visual Studio and can only offer assistance in how to use our API functions.
B. Similar steps apply for Microsoft Visual Studio 2008 (Express/Professional)edition. Before using any compiler, please check if the compiler is supported for the MATLAB Compiler version you are using. You can find this information here:
Related Question
- How to create a C – shared library with MATLAB Compiler 3.0 which can be used in other projects
- Mex -setup -v FORTRAN, Failure using R2014a with Win7, MSVS2013 sp1 and Intel Fotran Composer 2013 SP1
- How to create a C shared library with MATLAB Compiler 4.0 (R14) that can be used in a Microsoft .NET 2003 project
- How to setup Visual Studio Professional 2013 as the compiler for mex -setup Matlab 2015b
- How to create a C shared library using MATLAB Compiler 6.5 (R13) and use it with the C application
Best Answer