Main Content

Use Dynamically Allocated C++ Arrays in Generated Function Interfaces

In most cases, when you generate code for a MATLAB®function that accepts or returns an array, there is an array at the interface of the generated C/C++ function. For an array size that is unknown at compile time, or whose bound exceeds a predefined threshold, the memory for the generated array is dynamically allocated on the heap. Otherwise, the memory of the generated array is statically allocated on the stack. SeeControl Memory Allocation for Variable-Size Arrays.

If you choose C++ as your target language for code generation, by default, the dynamically allocated array is implemented as a class template calledcoder::arrayin the generated code. To use dynamically allocated arrays in your custom C++ code that you integrate with the generated C++ functions, learn to use thecoder::arraytemplate.

Using thecoder::arrayClass Template

When you generate C++ code for your MATLAB functions, the code generator produces a header filecoder_array.hin the build folder. This header file contains the definition of the class templatearrayin the namespacecoder. Thecoder::arraytemplate implements the dynamically allocated arrays in the generated code. The declaration for this template is:

template  class array
The array contains elements of typeTand hasNdimensions. For example, to declare a two-dimensional dynamic arraymyArraythat contains elements of typeint32_Tin your custom C++ code, use:

coder::array myArray

在您的自定义使用动态分配的数组C++ code that you want to integrate with the generated code (for example, a custom main function), include thecoder_array.hheader file in your custom.cppfiles. This table shows the API you use to create and interact with dynamic arrays in your custom C++ code.

Action

Instructions

Declare a dynamic arraymyArraythat contains elements of typeint32_T. Set the number of dimensions ofmyArrayto2.

Use thecoder::arraytemplate. Specify element type and number of dimensions.

coder::array myArray

Allocate memory formyArray. Set the size of the first dimension to1and the second dimension to100.

Use theset_sizemethod.

myArray.set_size(1, 100)

If the dimension ofmyArraychanges later on during execution, the generated code reallocates memory based on the new size.

Access the size vector ofmyArray.

Access thesizearray, which is a data member ofmyArray. For example, to access the size of the second dimension ofmyArray, use:

myArray.size(1)

Index into the dynamic arraymyArray.

Use the standard C++ syntax for array indexing. For example, to set thei-th element ofmyArrayequal toi, use:

myArray[i] = i

You can also index into multidimensional arrays by using the standard C++ syntax or use theatmethod.

myArray[我][j] =我*;/ /还可以使用“在”function myArray.at(i,j) = i * j;

Createcoder::arrayvariables fromstd::stringandstd::vectorarrays.

Use the copy constructor to createcoder::arrayarrays fromstd::stringandstd::vectorarrays. For example, to create acoder::arraycopy of thestd::vectorarrayvec, use:

std::vector vec; // Create coder::array copy coder::array copyArray(vec);

UsecopyArrayto interface the generated code with your project.

Examples

The following examples show how to generate C++ code that accepts and returns variable-size numeric and character arrays. To use dynamically allocated arrays in your custom C++ code include thecoder_array.hheader file in your custom.cppfiles. Thecoder::arrayclass template has methods that allow you to allocate and free array memory.

You can also interface the generated code with arrays ofstd::vectororstd::stringas dynamic size arrays. These arrays can also be used as inputs to the generated functions. SeeGenerate C++ Code That Accepts and Returns a Variable-Size Vector of Characters.

Generate C++ Code That Accepts and Returns a Variable-Size Numeric Array

This examples shows how to customize the generated example main function to use thecoder::arrayclass template in your project. See the table above for information about its associated methods.

Your goal is to generate a C++ executable forxTest1that can accept and return an array ofint32_Telements. You want the first dimension of the array to be singleton and the second dimension to be unbounded.

  1. Define a MATLAB functionxTest1that accepts an arrayX, adds the scalarAto each of its elements, and returns the resulting arrayY.

    functionY = xTest1(X, A) Y = X;fori = 1:numel(X) Y(i) = X(i) + A;end
  2. Generate initial source code forxStringTestand movexTest1.hfrom the code generation folder to your current folder. Use the following commands:

    cfg = coder.config('lib'); cfg.TargetLang ='C++'; codegen-configcfg-args{ coder.typeof(int32(0), [1 inf]), int32(0)}xTest1.m-report

    The function prototype forxTest1in the generated code is shown here:

    void xTest1(const coder::array &X, int A, coder::array &Y)

    Interface the generated code by providing input and output arrays that are compatible with the function prototype shown above.

  3. Define a C++ main function in the filexTest1_main.cppin your current working folder.

    This main function includes the header filecoder_array.hthat contains thecoder::array类模板定义。主要的函数使用the API described in the table in the previous section to perform these actions:

    • DeclaremyArrayandmyResultas two-dimensional dynamic arrays ofint32_Telements.

    • Dynamically set the sizes of the two dimensions ofmyArrayto1and100by using theset_sizemethod.

    • Access the size vector ofmyResultby usingmyResult.size.

    #include #include #include int main(int argc, char *argv[]) { static_cast(argc); static_cast(argv); // Instantiate the input variable by using coder::array template coder::array myArray; // Allocate initial memory for the array myArray.set_size(1, 100); // Access array with standard C++ indexing for (int i = 0; i < myArray.size(1); i++) { myArray[i] = i; } // Instantiate the result variable by using coder::array template coder::array myResult; // Pass the input and result arrays to the generated function xTest1(myArray, 1000, myResult); for (int i = 0; i < myResult.size(1); i++) { if (i > 0) std::cout << " "; std::cout << myResult[i]; if (((i+1) % 10) == 0) std::cout << std::endl; } std::cout << std::endl; return 0; }
  4. Generate code by running this script:

    cfg = coder.config('exe'); cfg.TargetLang ='C++'; cfg.CustomSource ='xTest1_main.cpp'; cfg.CustomInclude ='.';%current working directorycodegen-configcfg-args{ coder.typeof(int32(0), [1 inf]), int32(0)}xTest1_main.cppxTest1.m-report

The code generator produces an executable filexTest1.exein your current working folder.

Generate C++ Code That Accepts and Returns a Variable-Size Vector of Characters

This example shows how to customize the generated example main file to interface string arrays with the generated code by using thecoder::arrayclass methods.

The main function in this example usesstd::vectorto declare the vectorvecofchar_Telements that you pass to the generated C++ functionxStringTest.

  1. Define a MATLAB functionxStringTestthat accepts a character vectorstr, insertsstrbetween the character vectors'hello 'and' world!', and returns the result. Your goal is to generate a C++ executable fromxStringTest.

    functiony = xStringTest(str) assert(isa(str,'char')); assert(size(str,1) == 1); assert(size(str,2) >= 0); y = ['hello 'str' world!'];
  2. Generate source code forxStringTestand movexStringTest.hfrom the code generation folder to your current working folder. Use the following commands:

    cfg = coder.config('lib'); cfg.TargetLang ='C++'; codegen-configcfg-args{coder.typeof(char('X'), [1 inf])}xStringTest.m-report

    In the report, check the function prototype forxStringTestin the generated code.

    void xStringTest(const coder::array &str, coder::array &y)

    Interface the generated code by providing input and output arrays that are compatible with the function prototype shown above.

  3. Define a C++ main function in the filexStringTest_main.cppin your current working folder.

    This main function uses defines the input array as anstd::vectorarray ofchar_T. Thefor-loop initializesvecwith character values from'A'to'J'. This array is the input to the generated function forxStringTest. The output of the function is returned in thecoder::arrayvariableresult.

    #include #include #include int main(int, char *[]) { // Instantiate the result variable by using coder::array template coder::array result; // Instantiate the input variable by using std::vector std::string vec; // Resize the input to include required values vec.resize(10); vec = "ABCDEFGHIJ"; // Pass the input and result arrays to the generated function interface xStringTest(vec, result); //Cast coder::array 'result' variable to std::string to display it std::cout << "Result is "; std::cout << static_cast(result) << std::endl; return 0; }
  4. Generate code by running this script.

    cfg = coder.config('exe'); cfg.TargetLang ='C++'; cfg.CustomSource ='xStringTest_main.cpp'; cfg.CustomInclude ='.';%current working directorycodegen-configcfg-args{coder.typeof(char('X'), [1 inf])}xStringTest_main.cppxStringTest.m-report

The code generator produces an executable filexStringTest.exein your current working folder.

Change Interface Generation

By default, the generated C++ code uses thecoder::arraytemplate to implement dynamically allocated arrays. Instead, you can choose to generate C++ code that uses the C styleemxArraydata structure to implement dynamically allocated arrays. To generate C styleemxArraydata structures, do one of the following:

To learn more about statically allocated arrays or dynamically allocated arrays implemented by using the C styleemxArraydata structure, seeUse C Arrays in the Generated Function Interfaces.

See Also

|

Related Topics