我想给我的mexFunction
一个任意大小的数组,但不知何故无法确定我的C代码中它的大小。我已经尝试sizeof(prhs[0])
(假设数组是第一个输入参数)但是这总是返回8 - 无论数组大小和类型如何。那么,有什么想法吗?我顺便使用Octave。
答案 0 :(得分:1)
由于您在评论中提到您尝试使用oct文件,所以这里是如何操作的(您仍应阅读oct-files上的手册部分):
$ cat foo.cc
#include <octave/oct.h>
DEFUN_DLD (foo, args, ,
"foo help text")
{
if (args.length () != 1)
{
print_usage ();
return octave_value_list ();
}
const NDArray m = args(0).array_value ();
if (error_state)
{
error ("foo: first input must be a numeric N dimensional array");
return octave_value_list ();
}
const dim_vector dims = m.dims ();
for (int i = 0; i < dims.length (); i++)
octave_stdout << "Dim " << i << " has length " << dims(i) << std::endl;
return octave_value_list ();
}
$ mkoctfile foo.cc
$ octave
octave:1> foo (rand (5, 3, 1, 2))
Dim 0 has length 5
Dim 1 has length 3
Dim 2 has length 1
Dim 3 has length 2
octave:2> foo ("bar")
error: invalid conversion from string to real N-d array
error: foo: first input must be a numeric N dimensional array
如果你真的想使用mex界面,这里是一个简化的版本,没有任何检查(如果输入错误,它将会出现段错误):
$ cat foo.c
#include "mex.h"
void
mexFunction (int nlhs, mxArray* plhs[],
int nrhs, const mxArray* prhs[])
{
const mwSize nd = mxGetNumberOfDimensions (prhs[0]);
const mwSize* dims = mxGetDimensions (prhs[0]);
for (int i = 0; i < nd; i++)
mexPrintf("Dim %i has length %i\n", i, dims[i]);
return;
}
$ mkoctfile --mex foo.c
$ octave
octave:1> foo (rand (5, 2, 3))
Dim 0 has length 5
Dim 1 has length 2
Dim 2 has length 3