MATLAB Answers

0

How do I create a C/C++ shared library with MATLAB Compiler that can be used in a Microsoft Visual C++ 2005 project using Windows Forms Application?

I would like to convert MATLAB files into a C/C++ shared library that can be called from my Microsoft Visual C/C++ project using Windows Forms Application.

3 Answers

Answer by MathWorks Support Team on 15 Jun 2018
 Accepted Answer

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:

  2 Comments

Important when using with Visual Studio 2013 and later: instead of calling
mclInitializeApplication(NULL,0)
call:
const char *args[] = {"-nojvm"};
const int count = sizeof(args) / sizeof(args[0]);
mclInitializeApplication(args, count))
Otherwise it crashes with access violation at foolibInitialize() call if started from VS environment.
Also take care:
mclTerminateApplication();
mylibTerminate();
must be called in opposite order: mclTerminateApplication() last. Order in example (see foolibTerminate() call) is correct.

Sign in to comment.


Answer by Yannis Kapsi on 28 Mar 2014

This is an awsome tutorial. Thank you. May I ask if I can share the produced library to a pc that has not a matlab installation?

  0 Comments

Sign in to comment.


Edited by David
on 17 Jan 2017

I am getting the following error
>> mcc -B csharedlib:mylib <MATLAB files> Picked up JAVA_TOOL_OPTIONS: -Djava.vendor="New Oracle" Depfun error: 'Unable to locate <MATLAB as a function on the MATLAB path' Error using mcc Error executing mcc, return status = 1 (0x1).

  1 Comment

Hi Suriya Prasanna Bhubalan
I understand that you are getting errors on trying to compile MATLAB function into C shared library. Please contact MathWorks Technical Support for assistance.
-Usha

Sign in to comment.