メインコンテンツ

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

参考

|

トピック