如何将整数值作为 mex 函数的输入传递?

How to pass as input of a mex function an integer value?

本文关键字:函数 输入 mex 整数      更新时间:2023-10-16

我试图传递一个mexfunction的参数,一个整数,表示mxCreateDoubleMatrix的列数。这个整数不应该在主 mexFunction 之外的任何地方使用。

不知何故,这似乎不起作用。


// mex function for calling c++ code .
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
char *input_buf;
size_t buflen;
double ncols;
double *result_final;
double *result_second;
/* get the length of the input string */
buflen = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1;
/* copy the string data from prhs[0] into a C string input_ buf.    */
input_buf = mxArrayToString(prhs[0]);
/* copy the int from prhs[0] to decide on length of the results.    */
ncols = (int) (size_t) mxGetPr(prhs[1]);
plhs[0] = mxCreateDoubleMatrix(1, ncols, mxREAL);
plhs[1] = mxCreateDoubleMatrix(1, ncols, mxREAL);
result_final = mxGetPr(plhs[0]);
result_second = mxGetPr(plhs[1]);
/* Do the actual computations in a subroutine */
subroutine(input_buf, buflen, result_final, result_second);
}

如果我取出 ncols 线,其余所有内容都按预期工作。我没有将 ncols 作为子例程的输入,因为它实际上并没有在那里使用,而只是在 main 中用于定义输出数组的大小。

如果我调用 myfun('examplefile.txt',100),则输出数组的矩阵应该有一个 1x100 的矩阵,而不是调用结束时显示的矩阵具有无限/非常长的列数。

有人可以帮忙吗?

您正在将指向值的指针转换为size_t,然后转换为int。但它是一个指针,RAM中值位置的地址,而不是值本身。

ncols = (int) (size_t) mxGetPr(prhs[1]); %mex Get Pointer!!

改为获取值。

ncols = (int)(mxGetScalar(prhs[1]));