Skip to Main Content Skip to Search
Product Documentation

C Shared Library Target

C Shared Library Wrapper

The C library wrapper option allows you to create a shared library from an arbitrary set of MATLAB files on both Microsoft Windows and UNIX operating systems. MATLAB Compiler generates a wrapper file, a header file, and an export list. The header file contains all of the entry points for all of the compiled MATLAB functions. The export list contains the set of symbols that are exported from a C shared library.

C Shared Library Example

This example takes several MATLAB files and creates a C shared library. It also includes a standalone driver application to call the shared library.

Building the Shared Library

  1. Copy the following files from matlabroot/extern/examples/compiler to your work directory:

    matlabroot/extern/examples/compiler/addmatrix.m
    matlabroot/extern/examples/compiler/multiplymatrix.m
    matlabroot/extern/examples/compiler/eigmatrix.m
    matlabroot/extern/examples/compiler/matrixdriver.c
    

      Note   matrixdriver.c contains the standalone application's main function.

  2. To create the shared library, enter the following command on a single line:

    mcc -B csharedlib:libmatrix addmatrix.m multiplymatrix.m 
    eigmatrix.m -v
    

    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. Note the directory where the product puts the shared library because you will need it later on.

Writing the Driver Application

All programs that call MATLAB Compiler generated shared libraries have roughly the same structure:

  1. Declare variables and process/validate input arguments.

  2. Call mclInitializeApplication, and test for success. This function sets up the global MCR state and enables the construction of MCR instances.

      Caution   Avoid issuing cd commands from the driver application prior to calling mclInitializeApplication. Failure to do so can cause a failure in MCR initialization.

  3. Call, once for each library, <libraryname>Initialize, to create the MCR instance required by the library.

  4. Invoke functions in the library, and process the results. (This is the main body of the program.)

      Note   If your driver application displays MATLAB figure windows, you should include a call to mclWaitForFiguresToDie(NULL) before calling the Terminate functions and mclTerminateApplication in the following two steps.

  5. Call, once for each library, <lib>Terminate, to destroy the associated MCR.

      Caution   <lib>Terminate will bring down enough of the MCR address space that the same library (or any other library) cannot be initialized. Issuing a <lib>Initialize call after a <lib>Terminate call causes unpredictable results. Instead, use the following structure:

      ...code... 
      mclInitializeApplication(); 
      lib1Initialize(); 
      lib2Initialize(); 
      
      lib1Terminate(); 
      lib2Terminate(); 
      mclTerminateApplication(); 
      ...code... 

  6. Call mclTerminateApplication to free resources associated with the global MCR state.

  7. Clean up variables, close files, etc., and exit.

This example uses matrixdriver.c as the driver application.

Linking to mclmcrrt.lib: How the MCLMCRRT Proxy Layer Handles Loading of Libraries in \bin.  All application and software components generated by MATLAB Compiler and the associated builder products need to link against only one MathWorks library, mclmcrrtxx.lib. This versioned library (with the version represented by xx) provides a proxy API for all the public functions in MATLAB libraries used for matrix operations, MAT-file access, utility and memory management, and application runtime.

The relationship between mclmcrrtxx.lib and other MATLAB modules is shown in the following figure.

The MCLMCRRT Proxy Layer

The MCLMCRRT Proxy Layer graphic depicts solid arrows designating static linking and dotted arrows designating dynamic linking.

The MCLMCRRT module lies between deployed components and other modules, providing the following functionality:

Other Details.  

In addition, the figure shows that the MCLMCR contains the run-time functionality of the deployed components. Additionally, the MCR module ensures each deployed component runs in its own context at runtime. mclmcrrtxx.lib, in addition to loading the MCLMCR, also dynamically loads the MX and MAT modules, primarily for mxArray manipulation.

For more information, see the MathWorks Support database and search for information on the MSVC shared library.

Compiling the Driver Application

To compile the driver code, matrixdriver.c, you use your C/C++ compiler. Execute the following mbuild command that corresponds to your development platform. This command uses your C/C++ compiler to compile the code.

mbuild matrixdriver.c libmatrix.lib    (Windows)
mbuild matrixdriver.c -L. -lmatrix -I. (UNIX)

This generates a standalone application, matrixdriver.exe, on Windows, and matrixdriver, on UNIX.

Difference in the Exported Function Signature.  The interface to the mlf functions generated by MATLAB Compiler from your MATLAB file routines has changed from earlier versions of the product. The generic signature of the exported mlf functions is

Refer to the header file generated for your library for the exact signature of the exported function. For example, in the library created in the previous section, the signature of the exported addmatrix function is

void mlfAddmatrix(int nlhs,mxArray **a,mxArray *a1,mxArray *a2);

Testing the Driver Application

These steps test your standalone driver application and shared library on your development machine.

  1. To run the standalone application, add the directory containing the shared library that was created in step 2 in Building the Shared Library to your dynamic library path.

  2. Update the path for your platform by following the instructions in .

  3. Run the driver application from the prompt (DOS prompt on Windows, shell prompt on UNIX) by typing the application name.

    matrixdriver.exe                             (On Windows)
    matrixdriver	                              (On UNIX)
    matrixdriver.app/Contents/MacOS/matrixdriver (On Maci64)

    The results are displayed as

    The value of added matrix is: 
    2.00		8.00		14.00	 
    4.00		10.00		16.00	 
    6.00		12.00		18.00	 
     
    The value of the multiplied matrix is: 
    30.00		66.00		102.00	 
    36.00		81.00		126.00	 
    42.00		96.00		150.00		 
     
    The eigenvalues of the first matrix are: 
    16.12		-1.12		-0.00	 

Creating Shared Libraries from C with mbuild

mbuild can also create shared libraries from C source code. If a file with the extension .exports is passed to mbuild, a shared library is built. The .exports file must be a text file, with each line containing either an exported symbol name, or starting with a # or * in the first column (in which case it is treated as a comment line). If multiple .exports files are specified, all symbol names in all specified .exports files are exported.

Deploying Standalone Applications That Call MATLAB Compiler Based Shared Libraries

Gather and package the following files and distribute them to the deployment machine.

Component

Description

MCR Installer

Self-extracting MATLAB Compiler Runtime library utility; platform-dependent file that must correspond to the end user's platform. Run the mcrinstaller command to obtain name of executable.

matrixdriver

Application; matrixdriver.exe for Windows

matrixdriver.app for Maci64 (bundle directory structure must be deployed)

libmatrix

Shared library; extension varies by platform. Extensions are:

  • Windows — .dll

  • Linux, Linux x86-64 — .so

  • Mac OS X — .dylib

Deploying Shared Libraries to Be Used with Other Projects

To distribute the shared library for use with an external application, you need to distribute the following.

Component

Description

MCR Installer

(Windows) Self-extracting MATLAB Compiler Runtime library utility; platform-dependent file that must correspond to the end user's platform. Run the mcrinstaller command to obtain name of executable.

libmatrix

Shared library; extension varies by platform, for example, DLL on Windows

libmatrix.h

Library header file

Calling a Shared Library

At runtime, there is an MCR instance associated with each individual shared library. Consequently, if an application links against two MATLAB Compiler generated shared libraries, there will be two MCR instances created at runtime.

You can control the behavior of each MCR instance by using MCR options. The two classes of MCR options are global and local. Global MCR options are identical for each MCR instance in an application. Local MCR options may differ for MCR instances.

To use a shared library, you must use these functions:

Initializing and Terminating Your Application with mclInitializeApplication and mclTerminateApplication

mclInitializeApplication allows you to set the global MCR options. They apply equally to all MCR instances. You must set these options before creating your first MCR instance.

These functions are necessary because some MCR options such as whether or not to start Java, whether or not to use the MATLAB JIT feature, and so on, are set when the first MCR instance starts and cannot be changed by subsequent instances of the MCR.

The function signatures are

bool mclInitializeApplication(const char **options, int count);
bool mclTerminateApplication(void); 

mclInitializeApplication.  Takes an array of strings (options) that you set (the same options that can be provided to mcc via the -R option) and a count of the number of options (the length of the option array). Returns true for success and false for failure.

mclTerminateApplication.  Takes no arguments and can only be called after all MCR instances have been destroyed. Returns true for success and false for failure.

This C example shows typical usage of the functions:

int main(){
    
    mxArray *in1, *in2; /* Define input parameters */
    mxArray *out = NULL;/* and output parameters to pass to
                           the library functions */
    
    double data[] = {1,2,3,4,5,6,7,8,9};
    
    /* Call library initialization routine and make sure that
       the library was initialized properly */
    mclInitializeApplication(NULL,0);
    if (!libmatrixInitialize()){
        fprintf(stderr,"could not initialize the library 
                        properly\n");
        return -1;
    }

    /* Create the input data */
    in1 = mxCreateDoubleMatrix(3,3,mxREAL);
    in2 = mxCreateDoubleMatrix(3,3,mxREAL);
    memcpy(mxGetPr(in1), data, 9*sizeof(double));
    memcpy(mxGetPr(in2), data, 9*sizeof(double));
    
    /* Call the library function */
    mlfAddmatrix(1, &out, in1, in2);
    /* Display the return value of the library function */
    printf("The value of added matrix is:\n");
    display(out);
    /* Destroy return value since this variable will be reused
       in next function call. Since we are going to reuse the
       variable, we have to set it to NULL. Refer to MATLAB 
       Compiler documentation for more information on this. */
    mxDestroyArray(out); out=0;
    mlfMultiplymatrix(1, &out, in1, in2);
    printf("The value of the multiplied matrix is:\n");
    display(out);
    mxDestroyArray(out); out=0;
    mlfEigmatrix(1, &out, in1);
    printf("The Eigen value of the first matrix is:\n");
    display(out);
    mxDestroyArray(out); out=0;
    
    /* Call the library termination routine */
    libmatrixTerminate();
    
    /* Free the memory created */
    mxDestroyArray(in1); in1=0;
    mxDestroyArray(in2); in2 = 0;
    mclTerminateApplication();
    return 0;
}

Using a Shared Library

To use a MATLAB Compiler generated shared library in your application, you must perform the following steps:

  1. Include the generated header file for each library in your application. Each MATLAB Compiler generated shared library has an associated header file named libname.h, where libname is the library's name that was passed in on the command line when the library was compiled.

  2. Initialize the MATLAB libraries by calling the mclInitializeApplication API function. You must call this function once per application, and it must be called before calling any other MATLAB API functions, such as C-MEX functions or C MAT-file functions. mclInitializeApplication must be called before calling any functions in a MATLAB Compiler generated shared library. You may optionally pass in application-level options to this function. mclInitializeApplication returns a Boolean status code. A return value of true indicates successful initialization, and false indicates failure.

  3. For each MATLAB Compiler generated shared library that you include in your application, call the library's initialization function. This function performs several library-local initializations, such as unpacking the CTF archive, and starting an MCR instance with the necessary information to execute the code in that archive. The library initialization function will be named libnameInitialize(), where libname is the library's name that was passed in on the command line when the library was compiled. This function returns a Boolean status code. A return value of true indicates successful initialization, and false indicates failure.

      Note   On Windows, if you want to have your shared library call a MATLAB shared library (as generated by MATLAB Compiler), the MATLAB library initialization function (e.g., <libname>Initialize, <libname>Terminate, mclInitialize, mclTerminate) cannot be called from your shared library during the DllMain(DLL_ATTACH_PROCESS) call. This applies whether the intermediate shared library is implicitly or explicitly loaded. You must place the call somewhere after DllMain().

  4. Call the exported functions of each library as needed. Use the C MEX API to process input and output arguments for these functions.

  5. When your application no longer needs a given library, call the library's termination function. This function frees the resources associated with its MCR instance. The library termination function will be named <libname>Terminate(), where <libname> is the library's name that was passed in on the command line when the library was compiled. Once a library has been terminated, that library's exported functions should not be called again in the application.

  6. When your application no longer needs to call any MATLAB Compiler generated libraries, call the mclTerminateApplication API function. This function frees application-level resources used by the MCR. Once you call this function, no further calls can be made to MATLAB Compiler generated libraries in the application.

Using C Shared Libraries On a Mac OS X System

For information on using C shared libraries on a Macintosh system, see Using C/C++ Shared Libraries on a Mac OS X System.

  


Free MATLAB Compiler Interactive Kit

Learn how to build standalone executables and C/C++ shared libraries from MATLAB code.


Get free kit

Trials Available

Try the latest version of MATLAB Compiler.


Get trial software
 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS