【发布时间】:2015-06-09 22:16:12
【问题描述】:
我有以下 .m 文件(名为 testmemoryallocation.m),用于在 Matlab Coder 中生成代码。当然,这只是一个演示概念的测试文件。
function output = testmemoryallocation(dim) %#codegen
%TESTMEMORYALLOCATION Tests allocation of large 3D arrays
output = coder.nullcopy(zeros([dim, dim, dim]));
output(:) = 5;
end
我使用以下构建脚本(来自 Coder 应用程序的默认设置)构建它
%% Create configuration object of class 'coder.CodeConfig'.
cfg = coder.config('lib','ecoder',false);
cfg.GenerateReport = true;
cfg.GenCodeOnly = true;
cfg.HardwareImplementation = coder.HardwareImplementation;
cfg.HardwareImplementation.ProdIntDivRoundTo = 'Undefined';
cfg.HardwareImplementation.TargetIntDivRoundTo = 'Undefined';
%% Define argument types for entry-point 'testmemoryallocation'.
ARGS = cell(1,1);
ARGS{1} = cell(1,1);
ARGS{1}{1} = coder.typeof(0);
%% Invoke MATLAB Coder.
codegen -config cfg testmemoryallocation -args ARGS{1}
此构建过程生成的 C 代码如下所示:
/*
* testmemoryallocation.c
*
* Code generation for function 'testmemoryallocation'
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "testmemoryallocation.h"
#include "testmemoryallocation_emxutil.h"
/* Function Definitions */
void testmemoryallocation(double dim, emxArray_real_T *output)
{
int i0;
int loop_ub;
/* TESTMEMORYALLOCATION Tests allocation of large 3D arrays */
i0 = output->size[0] * output->size[1] * output->size[2];
output->size[0] = (int)dim;
emxEnsureCapacity((emxArray__common *)output, i0, (int)sizeof(double));
i0 = output->size[0] * output->size[1] * output->size[2];
output->size[1] = (int)dim;
emxEnsureCapacity((emxArray__common *)output, i0, (int)sizeof(double));
i0 = output->size[0] * output->size[1] * output->size[2];
output->size[2] = (int)dim;
emxEnsureCapacity((emxArray__common *)output, i0, (int)sizeof(double));
loop_ub = (int)dim * (int)dim * (int)dim;
for (i0 = 0; i0 < loop_ub; i0++) {
output->data[i0] = 5.0;
}
}
/* End of code generation (testmemoryallocation.c) */
问题是:在 MATLAB Coder 中(在testmemoryallocation.m 文件中)有没有办法验证内存是否已实际分配?内存分配发生在 emxEnsureCapacity 函数中,它本身不会返回有关成功分配的信息(据我所知)。如果没有足够的系统内存,我希望能够从调用函数中正常退出完成该过程。例如,我想向 testmemoryallocation 添加一个result 输出,指示分配内存时是否发生错误。有没有办法做到这一点?
真的,问题归结为:有没有办法访问 emxArrays 来测试结构的 data 字段不为空。也许是一个用 coder.ceval 调用的 .c 文件?有没有办法指示 coder.ceval 传递 emxArray 类型而不是基类型(double 或 int),以便编写底层 .c 代码以与结构交互?
编辑:
接受的出色答案既解决了这个问题,也解决了 (2015a) Coder 中生成的 c 代码中的一个潜在错误。在 _emxutil 文件中,如果请求的元素数量大于 intmax/2,则 emxEnsureCapacity 函数可能会出现无限循环。
【问题讨论】:
标签: matlab memory-management matlab-coder