我这里有一个非常基本的 mex 文件示例:
#include "mex.h"
#include "matrix.h"
void createStructureArray(mxArray* main_array)
{
const char* Title[] = { "first", "second" };
main_array = mxCreateStructMatrix(1,1, 2, Title);
}
void mexFunction(mwSize nlhs, mxArray *plhs[], mwSize nrhs,
const mxArray *prhs[])
{
double* x = mxGetPr(prhs[0]);
if (*x < 1.0)
{
//This works
const char* Title[] = { "first", "second" };
plhs[0] = mxCreateStructMatrix(1,1, 2, Title);
}
else
{
//This does not
createStructureArray(plhs[0]);
}
}
此函数应始终返回一个包含元素 first
和 second
的结构。无论输入如何,我都期望相同的输出。但是,如果输入参数 < 1,一切都会按预期工作,但是 > 1 我收到一条错误消息:
>> a = easy_example(0.0)
a =
first: []
second: []
>> a = easy_example(2.0)
One or more output arguments not assigned during call to "easy_example".
因此,我不能在 mexFunction
之外调用 mxCreateStructMatrix
函数吗?还是我在传递指针时做错了什么?
最佳答案
您对 mex
没有问题,但对指针有问题!
尝试将您的功能更改为:
void createStructureArray(mxArray** main_array)
{
const char* Title[] = { "first", "second" };
*main_array = mxCreateStructMatrix(1,1, 2, Title);
}
以及函数调用
createStructureArray(&plhs[0]);
您的问题是 plhs[0]
是一个 mxArray
,但为了返回它,您需要将指针传递给该 mxArray
!
关于matlab - 墨西哥文件 : mxCreateXXX only inside main mexFunction()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081236/