1)首先我们要写一个接口函数mexFunction(),这个接口函数就是类似C++的main函数,它是入口函数,传递参数给我们的C++函数。
#include "mex.h" //mx函数,mex函数用到的头文件
#include "exp.h"//调用函数用到的头文件
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
char *buff;
int M,N,state,len;
//if (nlhs>1)
//mexErrMsgTxt("Too many output argument!");
if (nrhs!=1)
{
mexErrMsgTxt("Must have two input argument!");
}
//prhs[0] = mxCreateString(a);
M = mxGetM(prhs[0]);//获得输入参数的行
N = mxGetN(prhs[0]);//获得输入参数的列
len = M*N+1;
buff = (char*)mxCalloc(len,sizeof(char));//申请内存空间,mxCalloc类是C语言的Calloc
state = mxGetString(prhs[0],buff,len);//把prhs[0]由mxArray类型字符转换为char类型
if (state!=0)
mexWarnMsgTxt("Not enough space. String is truncated.");
print(buff);//调用写好的C++函数,我们传递的是字符指针
}
2)接下来写C++函数了,记住C++函数要单独一个CPP文件,这样有利与之后的mex文件编译。
//print.cpp
#include "exp.h"
#include "mex.h"
void print (char *a)
{
mexPrintf ("%s jiangfeng\n",a);
Array();//函数的嵌套调用
}
//Array.cpp
#include "exp.h"
void Array()
{
int i,a[10]={1,2,3,4,5,6,7,9,8,0};
for (i=0;i<10;i++)
{
mexPrintf ("%d ",a[i]);
}
mexPrintf ("\n");
test();//函数嵌套调用
}
//test.cpp
#include "exp.h"
void test()
{
mexPrintf ("very good !\n");
}
//exp.h
#ifndef EXP_H
#define EXP_H
#include "mex.h"
void print (char *a);
void Array();
void test();
#endif
3)编译C++代码生成mex文件mex print.cpp Array.cpp test.cpp mexFunction.cpp
之后产生print.mexa64文件,这个文件可以在matlab下直接运行,如:
>>print(‘hello world’)
hello world jiangfeng
1 2 3 4 5 6 7 8 9 0
very good !
>>
如果在mex print.cpp Array.cpp test.cpp mexFunction.cpp 过程中出现下面错误,如:
Mex file entry point is missing. Please check the (case-sensitive)
spelling of mexFunction (for C MEX-files), or the (case-insensitive)
spelling of MEXFUNCTION (for FORTRAN MEX-files).
这种错误说明mexFunction()的参数格式不正确,应该严格按照格式书写
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
well done