주요 콘텐츠

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라는 이름의 폴더 내에 파일을 생성합니다. 생성되는 파일에 대한 자세한 내용은 Files Generated After Packaging MATLAB Functions 항목을 참조하십시오.

    참고

    생성된 라이브러리는 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

참고 항목

|

도움말 항목