Matlab 教材:測試 MEX-file

在 C 程式語言中,有一個最沒營養,也是最簡單的程式:「Hello,world.」。 為了符合傳統,我們就從這個程式開始。

首先,請讀者下載這個檔案:

Hello,world.
然後打開 Matlab,移動到這個檔案所在的目錄,下指令
mex hello.c
如果讀者設定了合適的編譯器,matlab 會自動幫我們編譯這個程式。 編譯完成以後,讀者可以試著下指令
hello
沒出錯的話,Matlab 會說:「Hello,world.」。

由上面的操作可以知道:Matlab 建立一個 subroutine 的指令是

mex filename
Matlab 會透過檔案副檔名判斷這個 subroutine 是由哪個程式語言寫成。 編譯之後,Matlab 會建立一個跟原始碼檔案同名的 DLL 檔, 輸入這個檔案的名字,Matlab 會自動呼叫 subroutine。

現在我們了解從一個原始碼變成一個 subroutine 的過程, 那接著就是要寫出原始碼。 下面是 hello.c 的原始碼:

#include <stdio.h>
#include "mex.h"
  
void mexFunction(int nlhs,mxArray *plhs[], int nrhs, const mxArray *prhs[]){
    printf("Hello, world.");
}
看起來跟一般的 C 程式語言很像,這裡有兩個重點。 第一個重點是
#include "mex.h"
mex.h 定義了所有 Matlab 和 C 溝通所用到的 subroutine, 因此所有寫給 Matlab 呼叫的 C 程式都應該包含這一列。 第二個重點是
void mexFunction(int nlhs,mxArray *plhs[],
    int nrhs, const mxArray *prhs[])
mexFunction 是程式的進入點,等價於 ANSI C 的 main, 所以這是一定要被用到的 subroutine。 mexFunction 的定義由 mex.h 提供,所以即使是像 hello,world 這樣簡單的程式, 我們還是要 include mex.h。

[BCC16-B]
李易霖 (2004/08/04) ---
[Prev] [Next] [Up]