Matlab與C++混合MEX程式設計
阿新 • • 發佈:2019-02-19
一、mexFunction
與C中的main函式一樣,MEX程式中的開始函式為mexFunction.預設變數引數是:
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
其中
nlhs指的是在呼叫函式時返回值的個數;
plhs[]是每個返回值(在MATLAB中都是矩陣)的指標;
nrhs指的是呼叫函式時的引數個數;
prhs[]是每個引數的指標。
在函式內部呼叫時,常用函式用法如下:
mxIsNumeric(prhs[0]); // 判斷變數是否是數字
mxIsDouble(prhs[0]); // 判斷變數是否為雙精度
mxIsEmpty(prhs[0]); // 判斷變數是否為空值
mxIsComplex(prhs[0]); // 判斷變數是否為複數
mexPrintf("%d", y); // 命令列中列印資料
x = mxGetN(prhs[0]); // 獲取各輸入引數的長度
y = mxGetM(prhs[1]); // 獲取輸入引數的列數
points = mxGetScalar(prhs[1]); // 將返回變數的實部,為雙精度形資料
plhs[0]= mxCreateDoubleMatrix(1, 1, mxREAL); // 建立1×1雙精度返回變數
x = mxGetData(prhs[0]); // 獲取變數的指標,功能相當於mxGetPr()
y = mxGetPr(plhs[0]); // 獲取變數的指標,資料為實數
對mexFunction的引數是進行指標操作的,不能用單純的return返回值。MEX程式傳送回來的整數資料要變為雙精度型資料,才能為其它函式所處理。
二、例子:對MaxPooling.cpp與StochasticPooling.cpp的編譯
if exist('MaxPooling')~=3
mex MaxPooling.cpp COMPFLAGS="/openmp $COMPFLAGS" CXXFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" -largeArrayDims
end;
if exist('StochasticPooling')~=3
mex StochasticPooling.cpp COMPFLAGS="/openmp $COMPFLAGS" CXXFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" -largeArrayDims
end;
轉自:http://blog.csdn.net/tina_lulu_21/article/details/7198941
mex MaxPooling.cpp COMPFLAGS="/openmp $COMPFLAGS" CXXFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" -largeArrayDims
end;
if exist('StochasticPooling')~=3
mex StochasticPooling.cpp COMPFLAGS="/openmp $COMPFLAGS" CXXFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp" -largeArrayDims
end;
轉自:http://blog.csdn.net/tina_lulu_21/article/details/7198941