基于C/C++语言的MEX文件应用

基于C/C++语言的一般MEX文件的内容如下:

#include "mex.h"
/*
 *注释部分
 *This is a MEX-file for MATLAB
*/
 /*The gateway function 入口函数*/
void mexFunction(int nlhs,mxArray *plhs[],
                  int nrhs,const mxArray *prhs[])
{
	/*variable declarations here 变量声明*/
	/*code here */
}

从上面的程序中可以明显地看到,这个文件是一个典型的C语言文件,其程序语法完全满足标准C语言的语法要求。然而,其在结构上却有独特之处。

  • 头文件的包含语句。所有的源文件中必须包含mex.h,该头文件完成了所有C语言MEX函数的原型声明,还包含了matrix.h文件,即对mx函数和数据类型的声明与定义。
  • C语言MEX源文件的入口函数部分void mexFunction(int nlhs,mxArray *plhs[],int nrhs,xonst mxArray *prhs[])。这是MEX文件的必需部分,并且书写形式固定:括号;里的4个变量分别表示输出参数的个数,输出参数,输入参数的个数和输入参数。
程序中,输入/输出参数的类型均为mxArray,或者可以用中文称为“阵列”。阵列是MATLAB唯一能处理的对象;在C语言程序变形的MEX文件中,MATLAB阵列用结构体mxArray定义。

void arrayProduct(double x,double *y,double *z,int n)
{
	int i;
	for(i=0;i<n;i++){
		z[i]=x*y[i];
	}
}
上面是使用C/C++语言编程实现的方法,下面介绍使用MEX文件实现上述功能的方法。使用MATLAB通过调用MEX文件实现上述功能的步骤包括:

  1. 定义宏。
  2. 创建MEX源文件计算程序。
  3. 创建入口函数程序。
  4. 检查输入参数和输出参数。
  5. 读取输入数据。
  6. 准备输出数据。
  7. 进行计算。
  8. 编译链接生成MEX二进制文件。
  9. 测试MEX文件。
具体命令及其实现步骤如下:
/*1. Use Macro 使用宏包括头文件*/
#include "mex.h"
/*2. The computational routine 计算程序*/
void arrayProduct(double x,double *y,double *z,int n)
{
	int i;
	for(i=0;i<n;i++){
		z[i]=x*y[i];
	}
}
void mexFunction(int nlhs,mxArray *plhs,int nrhs, 
		         const mxArray *prhs[])
{
	double multiplier;
	double *inMatrix;
	size_t ncols;
	double *outMatrix;
	/* check for proper number of arguments 检查参数*/
	if (nrhs!=2){
		mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","Two inputs required.");
	}
	if (nlhs!=1){
		mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs","One outputs required.");
	}
	/*4. make sure the first input argument is a scalar 确定第一个参数为标量*/
	if (!mxIsDouble(prhs[0])||mxIsComplex(prhs[0])||
		mxGetNumberofElements(prhs[0])!=1) {
		mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notScalar","Input multiplier must be a scalar.");
	}
	/*5. get the value of the scalar input 获取参数*/
	multiplier=mxGetScalar(prhs[0]);
	/* create a pointer to the real data in the input matrix */
	inMatrix=mxGetPr(prhs[1]);
	/* get dimensions of the input matrix */
	ncols=mxGetN(prhs[1]);
	/* create the output matrix */
	plhs[0]=mexCreateDoubleMatrix(1,(mwSize)ncols,mxREAL);
	/* get a pointer to the real data in the output matrix */
	outMatrix=mxGetPr(plhs[0]);
	/* 6. call the computational routine */
	arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值