Simulink 嵌入式 MATLAB 函数:为自定义 C/C++ 函数使用无头文件的 coder.cinclude()
众所周知,可以在嵌入式 MATLAB 函数中将 coder.ceval(...) 与 coder.cinclude(...) 结合使用,以调用外部 C/C++ 函数:
mysquare_header_included.m
function y = mysquare(x) %#codegen
coder.cinclude('mysquare.h');
y = 0.0;
coder.ceval('mysquare', coder.ref(x), coder.wref(y));
end鲜为人知的是,你可以在 coder.cinclude() 调用中“内联”包含 C/C++ 代码,虽然这种做法略显取巧。这种方式非常实用,因为这样就不必专门管理头文件了。
请注意,在编译模型时,Simulink/MATLAB Coder 仍会检查代码能否正确编译,因此你需要确保代码能够进行“独立”编译。
mysquare_headerless_inline.m
function y = mysquare(x) %#codegen
% 使用 coder.cinclude() 的作用只是将内容包含到文件顶部,
% 因此我们可以借用它来包含整个函数,而不仅仅是头文件包含。
coder.cinclude(sprintf(...
['<math.h>\n' ... % 占位 include,用于结束 #include 行
'inline void mysquare(const double* x, double* y) {\n' ...
' *y = (*x) * (*x);\n' ...
'}'] ...
));
y = 0.0;
coder.ceval('mysquare', coder.ref(x), coder.wref(y));
end切记,使用占位的 <math.h> include 来结束 #include 行是绝对必要的!
这会在头文件中生成如下代码:
mysquare_generated_header.cpp
#include <math.h>
inline void mysquare(const double* x, double* y)
{
*y = (*x) * (*x);
}并且在开启足够多的注释级别后,生成的 .cpp 文件中会包含如下代码:
mysquare_generated_cpp_snippet.cpp
/* MATLAB Function 'Logic/S-Process emulation/MATLAB Function1': '<S7>:1' */
/* '<S7>:1:5' coder.cinclude(sprintf(... */
/* '<S7>:1:6' ['<math.h>\n' ... % Dummy include to terminate the #include line */
/* '<S7>:1:7' 'inline void mysquare(const double* x, double* y) {\n' ... */
/* '<S7>:1:8' ' *y = (*x) * (*x);\n' ... */
/* '<S7>:1:9' '}'] ... */
/* '<S7>:1:10' )); */
/* '<S7>:1:11' y = 0.0; */
/* '<S7>:1:12' coder.ceval('mysquare', coder.ref(x), coder.wref(y)); */
mysquare(&rtb_y_l, &rtb_y);Check out similar posts by category:
MATLAB/Simulink
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow