|
%Matlab R2009a
Matlab可以將C程序編譯為MEX文件供Matlab調用,第一步是在Matlab的Command Window下輸入命令mex- setup,并根據Matlab的提示選擇合適的選項,如下所示(加粗部分為用戶輸入)。
>> mex -setup
Please choose your compiler for building external interface (MEX) files:
Would you like mex to locate installed compilers [y]/n? y
Select a compiler:
[1] Lcc-win32 C 2.4.1 in D:\PROGRA~1\MATLAB\R2009a\sys\lcc
[2] Microsoft Visual C++ 6.0 in C:\Program Files\Microsoft Visual Studio
[0] None
Compiler: 2
Please verify your choices:
Compiler: Microsoft Visual C++ 6.0
Location: C:\Program Files\Microsoft Visual Studio
Are these correct [y]/n? y
Trying to update options file: C:\Documents and Settings\yjsjf\Application Data\MathWorks\MATLAB\R2009a\mexopts.bat
From template: D:\PROGRA~1\MATLAB\R2009a\bin\win32\mexopts\msvc60opts.bat
Done . . .
**************************************************************************
Warning: The MATLAB C and Fortran API has changed to support MATLAB
variables with more than 2^32-1 elements. In the near future
you will be required to update your code to utilize the new
API. You can find more information about this at:
http://www.mathworks.com/support ... l?solution=1-5C27B9
Building with the -largeArrayDims option enables the new API.
**************************************************************************
>>
接下來是寫C文件,在Matlab的Command Window下輸入命令
>>edit hello.c
編輯文件內容并保存。
/*hello.c*/
#include "mex.h"
void mexFunction(int nlhs,mxArray* plhs[],int nrhs,const mxArray* prhs[])
{
mexPrintf("Hello World!\n");
}
下一步就是將C語言文件編譯為MEX文件
>> mex hello.c
編譯成功后可以在與hello.c文件相同的目錄下找到hello.mexw32文件,這就是編譯成功的MEX文件。
Tips:程序輸入錯誤的話,編譯不能成功,如將hello.c里面的
mexPrintf("Hello World!\n");
寫成了
mexPrint("Hello World!\n");
就會出現錯誤。。。像下面一樣
>> mex hello.c
Microsoft (R) Incremental Linker Version 6.00.8168
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
C:\DOCUME~1\YJSJF\LOCALS~1\TEMP\MEX_XN~1\hello.obj
Creating library C:\DOCUME~1\YJSJF\LOCALS~1\TEMP\MEX_XN~1\templib.x and object C:\DOCUME~1\YJSJF\LOCALS~1\TEMP\MEX_XN~1\templib.exp
hello.obj : error LNK2001: unresolved external symbol _mexPrint
hello.mexw32 : fatal error LNK1120: 1 unresolved externals
D:\PROGRA~1\MATLAB\R2009A\BIN\MEX.PL: Error: Link of 'hello.mexw32' failed.
??? Error using ==> mex at 218
Unable to complete successfully.
>>
====================================分割線=============================================
MEX文件結構說明
用C語言編寫MEX文件源代碼時,需要包含"mex.h"頭文件,像單片機要包含 "reg51.h"、"reg52.h"這些文件一樣,例外,代碼不是main函數作為入口函數,而是mexFunction這個函數,,即MEX源代碼基本結構就是這樣子。
#include "mex.h"
void mexFunction(int nlhs,mxArray* plhs[],int nrhs,const mxArray* prhs[])
{
}
其中,mexFunction函數的參數含義如下
int nlhs 輸出參數的個數
mxArray* plhs[] 輸出參數的mxArray數組
int nrhs 輸入參數的個數
const mxArray* prhs[] 輸入參數的mxArray數組
在Matlab中,所有的數據類型都使用mxArray結構來表示,通過接口函數mexFunction可以與Matlab環境進行數據交換。C語言的基本數據類型轉換為
mxArray類型是Matlab提供的一系列的操作mxArray的API函數完成的。其中以mx開頭的Matlab API函數主要提供對mxArray進行操作,以mex開頭的Matlab API函數提供Matlab環境后臺操作的函數。mex開頭的Matlab API函數只能在MEX文件中使用。
|
|