为什么在我的mex代码中,arraysize被识别为零?

时间:2017-01-01 21:43:21

标签: c++ matlab visual-c++ visual-studio-2013 mex

我有一个mex功能,我在matlab中使用以下命令(接口):

Matsize = 30555

Fv_calc(:,2) = mx_solve_quadratic(QuadraticCoefficients,MatSize);  

网关功能如下:

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    int *arraysizePtr = NULL;
    arraysizePtr = (int *)mxGetPr(prhs[1]);
    int arraysize = *arraysizePtr;
    float *inMatrix = NULL;
    inMatrix = (float *)mxGetPr(prhs[0]);
    const float a = 1; /* coefficient for x^2 is always 1*/
    plhs[0] = mxCreateNumericMatrix(arraysize, 1, mxSINGLE_CLASS, mxREAL);
    float *out = (float *)mxGetPr(plhs[0]);
    float x0; /* the smaller root */
    float x1; /* the bigger root */
    int fOutput = 0;
    int i = 0;
    for (i = 0; i < arraysize; i++)
    {
        fOutput = gsl_poly_solve_quadratic(a, inMatrix[i], inMatrix[i + arraysize], &x0, &x1);
        out[i] = (x1 > 0 ? x1 : 0);
    }
}  

一切都是真的,因为我之前已经运行过代码,现在我刚刚做了一些改动。 我真的不明白为什么在运行mex代码时,arraysize被识别为0

1 个答案:

答案 0 :(得分:1)

// Do not do this! Mother *mother; if(condition) { Child0 child; mother = &child; } mother->foo(); // <<<=== This is undefined behavior 似乎从我在网上找到的mxGetPr返回。

https://nl.mathworks.com/help/matlab/apiref/mxgetpr.html?s_tid=gn_loc_drop

通过double *进行转换并将其分配给int *arraysizePtr会导致double数据被解释为int,从而产生废话。