- 积分
- 92
- 注册时间
- 2003-5-19
- 仿真币
-
- 最后登录
- 1970-1-1
|
为了扩展MATLAB的功能,或者提高速度,我们通常会编写一些mex函数应用到matlab中。但是由于一个文件中只能包含一个mex函数,随着规模的扩大在一个程序中会存在很多个mex文件,而且这些文件一般都很小。当程序编译为脱离matlab的可执行程序时,这么多的mex文件会使得程序启动速度比较慢。那么有没有可能在一个mex文件中包含多个函数呢?本文的目的便在于此。
以将两个函数 Fun1 和 Fun2 为例演示如何将其合并到一个mex文件中。
实现步骤:
1. 添加头文件 "FunTable.h"
#include "FunTable.h"
2. 将原 mex 函数中的 mexFunction 成其它名字
3. 使用 ADD_TO_FUN_TABLE 将该函数加入到函数地址表中
4. 使用如下命令进行编译:
mex mexMultiFun.cpp Fun1.cpp Fun2.cpp
其中 Fun1.cpp 和 Fun2.cpp 为合并得 mex 函数原程序名称。
文件:Fun1.cpp- #include "mex.h"
- #include "FunTable.h"
- // 目标函数一
- void Fun1(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- {
- if(nrhs != 1) mexErrMsgTxt("需要一个输入参数!");
- if(nlhs != 1) mexErrMsgTxt("需要一个输出参数!");
- plhs[0] = mxDuplicateArray(prhs[0]);
- }
- // 添加到函数表中
- ADD_TO_FUN_TABLE("Fun1", Fun1)
复制代码 文件:Fun2.cpp- #include "mex.h"
- #include "FunTable.h"
- // 目标函数二
- void Fun2(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- {
- if(nrhs != 2) mexErrMsgTxt("需要两个输入参数!");
- if(nlhs != 2) mexErrMsgTxt("需要两个输出参数!");
- plhs[0] = mxDuplicateArray(prhs[0]);
- plhs[1] = mxDuplicateArray(prhs[1]);
- }
- // 添加到函数表中
- ADD_TO_FUN_TABLE("Fun2", Fun2)
复制代码 最后用 mex mexMultiFun.cpp Fun1.cpp Fun2.cpp 进行编译
合并后的函数调用方式如下:
A = mexMultiFun('Fun1', 1);
[B, C] = mexMultiFun('Fun2', 1, 2);
[ 本帖最后由 SCIE 于 2007-5-5 19:54 编辑 ] |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?注册
×
评分
-
1
查看全部评分
-
|