主要内容

本页采用了机器翻译。点击此处可查看英文原文。

使用 MATLAB 代码创建 C 共享库

R2026b

支持的平台:Windows®、Linux®、Mac

此示例说明如何使用 MATLAB® 函数创建 C 共享库。目标系统不需要 MATLAB 的许可副本。

在 MATLAB 中创建函数

  1. 在 MATLAB 中,检查您想要打包的 MATLAB 代码。

    对于此示例,将 MATLAB 附带的 matrix 文件夹复制到您的工作文件夹。

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

    导航到工作文件夹中的新 matrix 子文件夹。

  2. 检查并测试函数 addmatrix.m、multiplymatrix.m 和 eigmatrix.m。

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

    在 MATLAB 命令提示符下,输入 addmatrix([1 4 7; 2 5 8; 3 6 9], [1 4 7; 2 5 8; 3 6 9])。

    输出为:

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

    在 MATLAB 命令提示符下,输入 multiplymatrix([1 4 7; 2 5 8; 3 6 9], [1 4 7; 2 5 8; 3 6 9])。

    输出为:

     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

    在 MATLAB 命令提示符下,输入 eigmatrix([1 4 7; 2 5 8; 3 6 9])。

    输出为:

     ans =
       16.1168
       -1.1168
       -0.0000
    

使用 compiler.build.cSharedLibrary 创建 C 共享库

  • 使用 compiler.build.cSharedLibrary 函数编译 C 共享库。使用名称-值参量指定库名称并启用详尽输出。

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

    您可以使用名称-值参量在 compiler.build 命令中指定其他选项。有关详细信息,请参阅 compiler.build.cSharedLibrary。

    compiler.build.Results 对象 buildResults 包含有关编译类型、生成的文件、包含的支持包和编译选项的信息。

    该构建函数会在当前工作目录下的一个名为 libmatrixcSharedLibrary 的文件夹中生成文件。有关生成的文件的信息,请参阅 打包 MATLAB 函数后生成的文件。

    注意

    生成的库不包括 MATLAB Runtime 或安装程序。要使用 buildResults 对象创建安装程序,请参阅 compiler.package.installer。

在 C 应用程序中实现 C 共享库

打包 C 共享库后,您可以从 C 应用程序调用它。可以使用 C 应用程序代码调用共享库中包含的函数。

  1. 找到位于 matlabroot\extern\examples\compilersdk\c_cpp\matrix 或您的工作文件夹中的 matrix.c 文件。

    /*=================================================================
     *
     * 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);
    }
    
    

    将该文件复制并粘贴到包含 C 库文件(在 Windows 上为 libmatrix.lib,在 Mac 上为 libmatrix.dylib,在 Linux 上为 libmatrix.so)的文件夹中。

  2. 在 MATLAB 命令提示符下,导航到您复制 matrix.c 的文件夹。

  3. 使用 mbuild 编译并链接应用程序。

    mbuild matrix.c libmatrix.<ext>
  4. 要在 Linux 或 Mac 系统上运行应用程序,必须先将 MATLAB Runtime 添加到库路径。有关详细信息,请参阅为部署设置 MATLAB Runtime 库路径。

  5. 从系统命令提示符运行应用程序。在 Windows 上,将正斜杠替换为反斜杠 (\)。

    ./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

    注意

    您可能需要在 Linux 或 Mac 系统上为应用程序授予可执行权限。

    chmod u+x matrix

另请参阅

|

主题