此示例说明如何通过引用向外部 C 函数传递数据或传递来自外部 C 函数的数据。
通过引用传递是 C/C++ 代码集成的一种重要方法。通过引用传递数据时,程序不需要将数据从一个函数复制到另一个函数。通过值传递时,C 代码只能返回单个标量变量。通过引用传递时,C 代码可以返回多个变量,包括数组。
以 MATLAB 函数 adderRef 为例。此函数使用外部 C 代码将两个数组相加。coder.rref 和 coder.wref 命令指示代码生成器将指针传递给数组,而不是复制它们。
function out = adderRef(in1, in2)
%#codegen
out = zeros(size(in1));
% the input numel(in1) is converted to integer type
% to match the cAdd function signature
coder.ceval('cAdd', coder.rref(in1), coder.rref(in2), coder.wref(out), int32(numel(in1)) );
end
C 代码 cAdd.c 使用线性索引来访问数组的元素:
#include
#include
#include "cAdd.h"
void cAdd(const double* in1, const double* in2, double* out, int numel)
{
int i;
for (i=0; i
out[i] = in1[i] + in2[i];
}
}
要编译 C 代码,您必须提供带有函数签名的头文件 cAdd.h:
void cAdd(const double* in1, const double* in2, double* out, int numel);
通过生成 MEX 函数并将其输出与 MATLAB 中的加法运算的输出进行比较来测试 C 代码。
A = rand(2,2)+1;
B = rand(2,2)+10;
codegen adderRef -args {A, B} cAdd.c cAdd.h -report
if (adderRef_mex(A,B) - (A+B) == 0)
fprintf(['\n' 'adderRef was successful.']);
end
Code generation successful: To view the report, open('codegen/mex/adderRef/html/report.mldatx').
adderRef was successful.