Contenido principal

Create C Shared Library with MATLAB Code

R2026b

Supported platform: Windows®, Linux®, Mac

This example shows how to create a C shared library using a MATLAB® function. The target system does not require a licensed copy of MATLAB.

Create Functions in MATLAB

  1. In MATLAB, examine the MATLAB code that you want packaged.

    For this example, copy the matrix folder that ships with MATLAB to your work folder.

    copyfile(fullfile(matlabroot,'extern','examples','compilersdk','c_cpp','matrix'),'matrix')

    Navigate to the new matrix subfolder in your work folder.

  2. Examine and test the functions addmatrix.m, multiplymatrix.m, and eigmatrix.m.

    function a = addmatrix(a1, a2)
    
    a = a1 + a2;

    At the MATLAB command prompt, enter addmatrix([1 4 7; 2 5 8; 3 6 9], [1 4 7; 2 5 8; 3 6 9]).

    The output is:

     ans =
         2     8    14
         4    10    16
         6    12    18
    function m = multiplymatrix(a1, a2)
    
    m =  a1*a2;

    At the MATLAB command prompt, enter multiplymatrix([1 4 7; 2 5 8; 3 6 9], [1 4 7; 2 5 8; 3 6 9]).

    The output is:

     ans =
        30    66   102
        36    81   126
        42    96   150
    function e = eigmatrix(a1)
    
        try
            %Tries to calculate the eigenvalues and return them.
            e = eig(a1);
        catch
            %Returns a -1 on error.
            e = -1;
    end

    At the MATLAB command prompt, enter eigmatrix([1 4 7; 2 5 8; 3 6 9]).

    The output is:

     ans =
       16.1168
       -1.1168
       -0.0000
    

Create C Shared Library Using compiler.build.cSharedLibrary

  • Build the C shared library using the compiler.build.cSharedLibrary function. Use name-value arguments to specify the library name and enable verbose output.

    buildResults = compiler.build.cSharedLibrary(["addmatrix.m", ...
    "eigmatrix.m","multiplymatrix.m"], ...
    'LibraryName','libmatrix', ...
    'Verbose','on');

    You can specify additional options in the compiler.build command by using name-value arguments. For details, see compiler.build.cSharedLibrary.

    The compiler.build.Results object buildResults contains information on the build type, generated files, included support packages, and build options.

    The build function generates files within a folder named libmatrixcSharedLibrary in your current working directory. For information on the files generated, see Files Generated After Packaging MATLAB Functions.

    Note

    The generated library does not include MATLAB Runtime or an installer. To create an installer using the buildResults object, see compiler.package.installer.

Implement C Shared Library in C Application

After packaging your C shared library, you can call it from a C application. The C application code calls the functions included in the shared library.

  1. Locate the matrix.c file located in matlabroot\extern\examples\compilersdk\c_cpp\matrix or your work folder.

    /*=================================================================
     *
     * MATRIX.C Sample driver code that calls a shared library created
     *          using MATLAB Compiler SDK. Refer to the MATLAB Compiler 
     *          SDK documentation for more information.
     *
     * Copyright 1984-2022 The MathWorks, Inc.
     *
     *=================================================================*/
    
    #include <stdio.h>
    
    /* Include the MATLAB Runtime header file and the library specific header file 
     * as generated by MATLAB Compiler SDK. */
    #include "libmatrix.h"
    
    /* This function is used to display a double matrix stored in an mxArray */
    void display(const mxArray* in);
    
    int run_main(int argc, const char **argv)
    {
        mxArray *in1, *in2; /* Define input parameters */
        mxArray *out = NULL;/* and output parameters to be passed to the library functions */
        
        double data[] = {1,2,3,4,5,6,7,8,9};
        
        /* 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 initialization routine and make sure that the
         * library was initialized properly. */
        if (!libmatrixInitialize()){
            fprintf(stderr,"Could not initialize the library.\n");
            return -2;
        }
        else
        {
            /* Call the library function */
            mlfAddmatrix(1, &out, in1, in2);
            /* Display the return value of the library function */
            printf("The sum of the matrix with itself is:\n");
            display(out);
            /* Destroy the return value since this variable will be reused in
             * the next function call. Since we are going to reuse the variable,
             * we must set it to NULL. Refer to MATLAB Compiler SDK documentation
             * for more information. */
            mxDestroyArray(out); 
            out=0;
            mlfMultiplymatrix(1, &out, in1, in2);
            printf("The product of the matrix with itself is:\n");
            display(out);
            mxDestroyArray(out); 
            out=0;
            mlfEigmatrix(1, &out, in1);
            printf("The eigenvalues of the original matrix are:\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;
        }
    
        /* Note that you should call mclTerminateApplication at the end of
         * your application.
         */
        mclTerminateApplication();
        return 0;
    }
    
    
    /*DISPLAY This function will display the double matrix stored in an mxArray.
     * This function assumes that the mxArray passed as input contains double
     * array.
     */
    void display(const mxArray* in)
    {
        size_t i=0, j=0; /* loop index variables */
        size_t r=0, c=0; /* variables to store the row and column length of the matrix */
        double *data; /* variable to point to the double data stored within the mxArray */
    
        /* Get the size of the matrix */
        r = mxGetM(in);
        c = mxGetN(in);
        /* Get a pointer to the double data in mxArray */
        data = mxGetPr(in);
        
        /* Loop through the data and display it in matrix format */
        for( i = 0; i < c; i++ )
        {
            for( j = 0; j < r; j++)
            {
                printf("%4.2f\t",data[j*c+i]);
            }
            printf("\n");
        }
        printf("\n");
    }
    
    int main(int argc, const char ** argv)
    {
        /* Call the mclInitializeApplication routine. Make sure that the application
         * was initialized properly by checking the return status. This initialization
         * has to be done before calling any MATLAB APIs or MATLAB Compiler SDK
         * generated shared library functions.  */
        if( !mclInitializeApplication(NULL,0) )
        {
            fprintf(stderr, "Could not initialize the application.\n");
            return -1;
        }
        return mclRunMain((mclMainFcnType)run_main, argc, argv);
    }
    
    

    Copy and paste this file into the folder that contains your C library file (libmatrix.lib on Windows, libmatrix.dylib on Mac, libmatrix.so on Linux).

  2. At the MATLAB command prompt, navigate to the folder where you copied matrix.c.

  3. Use mbuild to compile and link the application.

    mbuild matrix.c libmatrix.<ext>
  4. To run the application on Linux or Mac systems, you must first add MATLAB Runtime to the library path. For details, see Set MATLAB Runtime Library Paths for Deployment.

  5. From the system command prompt, run the application. On Windows, replace the forward slash with a backslash (\).

    ./matrix
    The sum of the matrix with itself is: 
    2.00		8.00		14.00	 
    4.00		10.00		16.00	 
    6.00		12.00		18.00	 
     
    The product of the matrix with itself is: 
    30.00		66.00		102.00	 
    36.00		81.00		126.00	 
    42.00		96.00		150.00		 
     
    The eigenvalues of the original matrix are: 
    16.12		-1.12		-0.00

    Note

    You may need to give the application executable permissions on Linux or Mac systems.

    chmod u+x matrix

See Also

|

Topics