|
%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文件中使用。
|
|