MATLAB Answers

Can I access an external (const) array within generated C++ code without copying the contents into a local array?

18 ビュー (過去 30 日間)
Matt Shellhammer
Matt Shellhammer 2020 年 3 月 31 日
コメント済み: Matt Shellhammer 2020 年 3 月 31 日
I have been generating code with massive constant arrays in the generated code using MATLAB coder code generation MATLAB to C++ code. I would like to define these arrays in an external header funtion instead of within the MATLAB code, a MATLAB class, or define it as a global variable. I would like to define it as a const int array in a external header function and then just access that array in generated code (avoiding generating the array every time a change to the MATLAB code is modified).
I know that I could use an external function to copy the array into a local array, however my goal is to avoid copying the elements. I would like to simply directly access the elements from a const int array within generated code by using
coder.target('RTW')
if coder.target('RTW')
coder.cinclude('header.h');
% x defined in header.h (const int x[5] = {1,2,3,4,5};)
else
x = [1,2,3,4,5];
end
Any insight?

  0 件のコメント

サインインしてコメントする。

採用された回答

Ryan Livingston
Ryan Livingston 2020 年 3 月 31 日
編集済み: Ryan Livingston 2020 年 3 月 31 日
With Embedded Coder you can use the function coder.storageClass to pull in that array as an imported extern global variable:
function useImportedArray
global importedArray;
coder.storageClass('importedArray','ImportedExtern');
t = sum(importedArray(:));
fprintf('Sum = %g\n', t);
% Do codegen
cfg = coder.config('dll');
cfg.GenerateExampleMain = "GenerateCodeAndCompile";
codegen useImportedArray -config cfg -globals {'importedArray', [7,8,8]} arrayConstant.c
arrayConstant.c
const double importedArray[] = {1.0, 2.0, 3.0};

  3 件のコメント

Matt Shellhammer
Matt Shellhammer 2020 年 3 月 31 日
I tested this and the result is a definition of "extern int importedArray[3];", is there a way to get the extern variable to be a "extern const int importedArray[3];"? I would like to keep the array as a const int.
Ryan Livingston
Ryan Livingston 2020 年 3 月 31 日
Unfortunately there's not a way to make it const. I've made an internal note so we can think about that for the future though.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by