我正在matlab中學習mex檔案。我寫了這個簡單的代碼
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
double *outData, *inData;
if(nrhs!=2) mexErrMsgTxt("Missing input data.");
inData = mxGetDoubles(prhs[0]);
outData = mxGetDoubles(plhs[0]);
outData[0] = inData[0] inData[1];
}
但是當我嘗試運行它時,matlab 崩潰了。問題是最后一行,你有什么建議嗎?
謝謝
uj5u.com熱心網友回復:
plhs[0](即函式呼叫的左側指標)是輸出。
這個輸出變數沒有分配在記憶體中,你只有一個指向它的指標。因此,如果不先創建它,就不能在上面寫(也不能從中讀取)。
所以你需要類似的東西
const int ndims = 1; // or whatever dims you want
const mwSize dims[]={1}; // or whatever size you want
// create memory/variable
plhs[0] = mxCreateNumericArray(ndims ,dims,mxDOUBLE_CLASS,mxREAL);
// now it exists
outData = mxGetDoubles(plhs[0])
但是請注意,如果不輸入長度為 2 的陣列,inData[1]則將不存在,從而導致 RuntimeError,從而使 MATLAB 崩潰。因此,在訪問陣列之前檢查陣列的長度通常是一種好習慣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/449642.html
下一篇:如何創建2列單元陣列的所有排列?
