2017-01-25 38 views
1

我想寫一個簡單的mex函數。我有一個整數輸入,這是我的對象的數量。 當我編譯myMEX_1.cpp並通過MATLAB與任何輸入值調用它,我總是得到:使用mxGetPr vs mxGetData

Number請求的對象:= 0

myMEX_2.cpp工作正常,表明從MATLAB輸入的數命令窗口。 myMEX_1.cpp我的錯誤在哪裏?

我的環境:MATLAB R2013a和Microsoft SDK 7.1編譯器。

// myMEX_1.cpp 
#include "mex.h" 
void mexFunction(int nlhs,  mxArray *plhs[], 
       int nrhs, const mxArray *prhs[]) 
{ 

    char str11[100]; 
    unsigned short frameCount; 
    //unsigned short *frameCountPtr; 
    frameCount = (*((unsigned short*)mxGetData(prhs[0]))); 
    sprintf(str11, "Number of Requested Objects := %d:\n", frameCount); 
    mexPrintf(str11); 
} 





// myMEX_2.cpp 
#include "mex.h" 
void mexFunction(int nlhs,  mxArray *plhs[], 
       int nrhs, const mxArray *prhs[]) 
{ 
    char str11[100]; 
    unsigned short frameCount; 
    double* dblPointer; 
    dblPointer = mxGetPr(prhs[0]); 
    frameCount = (unsigned short)(*dblPointer); 
    sprintf(str11, "Number of Requested Objects := %d:\n", frameCount); 
    mexPrintf(str11); 
} 

回答

3

mxGetData返回void指針必須強制轉換爲正確數據類型的指針。

在C中,mxGetData返回void指針(void *)。由於void指針指向一個沒有類型的值,的返回值強制轉換爲指針類型,通過pm

在你的情況下指定的類型相匹配,我假設,雖然它看起來像你」它實際上是一個double,因爲這是MATLAB的默認數據類型,所以你的問題是由於你試圖將它轉換爲unsigned short指針。

myMEX_1(1)   % Passes a double 
myMEX_1(uint16(1)) % Passes an integer 

爲了解決這個問題,我們就需要轉換的mxGetData輸出爲double指針代替,然後取消對它的引用,投它併爲它分配

frameCount = (unsigned short)*(double*)mxGetData(prhs[0]); 

mxGetPr相同mxGetData除了它會自動將mxGetData的輸出作爲double指針投出。因此,它爲您節省了一個步驟,但僅適用於double輸入(您有)。

如果您想要適當地處理多種類型的輸入,則需要使用mxIsDoublemxIsClass來檢查輸入的類型。

if (mxIsDouble(prhs[0])) { 
    frameCount = (unsigned short)*mxGetPr(prhs[0]); 
} else if (mxIsClass(prhs[0], "uint16") { 
    frameCount = *(unsigned short*)mxGetData(prhs[0]); 
} else { 
    mexPrintf("Unknown datatype provided!"); 
    return; 
} 
+0

'mxGetPr'總是返回與輸入參數類型無關的'* double'。 – GntS

+0

@GmtK我認爲,但只是檢查出來。雖然你的代碼可以工作,如果你真的*傳遞一個整數:'myMEX_1(uint16(1))' – Suever

+0

函數原型在MATLAB幫助中作爲'double * mxGetPr(const mxArray * pm);' – GntS