Represent C++ Arrays Using MATLAB Objects - MATLAB & Simulink (original) (raw)
MATLAB® provides the clib.array
interface to wrap C++ native arrays and std::vector
types in MATLAB objects. The term clib array refers to the MATLAB object representation of these C++ types.
A MATLAB clib array is defined only when the corresponding C++ native array orstd::vector
type is used by supported C++ constructs—function input and output arguments and data members. The library header files must contain the definition of the array element type. The constructs must be supported by MATLAB and included when building the MATLAB interface to the C++ library.
This topic shows how to create a MATLAB clib array, use a clib array as a C++ function parameter, and convert a MATLAB array to a C++ array object. This topic also describes the common properties and methods of all MATLAB clib arrays.
Create MATLAB Array of C++ Objects
To create a MATLAB object that represents C++ native arrays or std::vector
types, call the MATLABclibArray function. For example, suppose that your interface libname
defines a class named MyClass
. In MATLAB, you refer to this class as clib.libname.MyClass
. Create an array of five MyClass
objects.
myclassArray = clibArray("clib.libname.MyClass",5);
The type of the MATLAB array myclassArray
isclib.array.libname.MyClass
. To access an element ofmyclassArray
, use MATLAB indexing. For example, access the first element.
The element type is clib.libname.MyClass
.
Alternatively, if the element type is a fundamental type, a user-defined class with a default constructor, or a standard string type, call the clib.array
constructor.
To create an array from a fundamental type, you must know the corresponding element type. For mapping information, see the Vector Integer Types and Floating Point Types tables inC++ to MATLAB Data Type Mapping. For example, if the C++ type is std::vector<int32_t>
, then the MATLAB element type is clib.libname.Int
. Create an array with fiveclib.libname.Int
elements.
myIntArray = clib.array.libname.Int(5)
Create an array of five elements of the same user-defined class.
myclassArray = clib.array.libname.MyClass(5)
To create an array from a standard string type, see the std::vector String Types table for element type information. For example, if the C++ type isstd::vector<std::string>
, then the MATLAB element type isclib.libname.std.String
. Create an array with fiveclib.libname.std.String
elements.
myStringArray = clib.array.libname.std.String(5)
Treat C++ Native Arrays of Fundamental Types as MATLAB Fundamental Types
By default, MATLAB represents C++ native arrays of fundamental types with the MATLABclib.array
types. If you need to preserve fundamental MATLAB array types with outputs, then build your MATLAB interface to the C++ library with the ReturnCArrays
name-value argument set to false
. For more information, seeclibgen.generateLibraryDefinition.
Note
Saving C++ objects into a MAT-file is not supported.
Note
You cannot create an array of C++ objects using square brackets.
Convert MATLAB Array to C++ Array Object
You can use an existing MATLAB array as a C++ array object. For example, suppose that you have a MATLAB interface libname
. Convert a MATLAB array of double
values to a C++ array object by using the clibConvertArray function.
a = [1 2 3]; arr = clibConvertArray("clib.libname.Double",a); class(arr)
'clib.array.libname.Double'
Call C++ Function with clib.array
Parameter
You can create a MATLAB variable to pass as a function parameter for specific C++ types. These examples show how to pass a clib array parameter directly, by reference, as a fixed-size array, and as const
and non-const
objects. The code assumes you build an interface named libname
.
Pass std::vector
Parameter
When you pass a clib array directly as a parameter to a C++ function that expects an std::vector
input, MATLAB converts the elements and the size of the clib array to anstd::vector
argument. The number of dimensions of the passed array must match the expected dimensions of the parameter. For example, this function takes an std::vector
of typedouble
.
void fcn(std::vector doubleVec);
Display the help text from MATLAB.
fcn - clib.libname.fcn Representation of C++ function fcn.
clib.libname.fcn(doubleVec) Input Arguments doubleVec vector clib.array.libname.Double
Create a 1-D clib array and pass it to fcn
.
arr1d = clibArray("clib.libname.Double",[3]) clib.libname.fcn(arr1d)
If you pass a 2-D array, MATLAB returns an error.
arr2d = clibArray("clib.libname.Double",[2 3]); arr2d.Dimensions
Error using clib.libname.fcn No method 'clib.libname.fcn' with matching signature found.
Pass struct
Parameter
Since R2024b
You can pass a MATLAB structure as a parameter to a C++ function. MATLAB converts the structure to a C++struct
argument. To view the C++ structure definition forMyStruct
in MATLAB, call help clib.libname.MyStruct
. The MATLAB structure must meet these requirements.
- The structure contains all of the fields of the C++ structure definition.
- The field names of the structure must exactly match the field names of the C++ structure. Field names are case-sensitive.
- The MATLAB structure cannot contain fields that are not in the C++ structure.
- The type for each field value must be a valid type for the matching field in the C++ structure.
- The size of the field value must match the C++ data member size.
For information about the C++ struct
, type help clib.libname.dataType
, where libname
is the MATLAB interface name and dataType
is thestruct
definition.
For example, this C++ code defines function getData
, which takes a struct
of type DataRecord
.
struct DataRecord {
char ID[5];
float amount;
double x;
};
void getData(DataRecord *s){};
Generate the library definition file for interface libname
, and define the getData
input argument as a two-element vector of typeclib.array.libname.DataRecord
. To define the argument, edit the defineArgument
function in thedefinelibname.m
file with the following values:
defineArgument(getDataDefinition, "s", "clib.array.libname.DataRecord", "input", 2);
After building the interface, display the help text forlibname
.
Classes contained in clib.libname: DataRecord - clib.libname.DataRecord Representation of C++ class DataRecord.
Functions contained in clib.libname: getData - clib.libname.getData Representation of C++ function getData.
Display the help text for the function getData
. The type for input s
is a two-element vector of typeclib.array.libname.DataRecord
.
help clib.libname.getData
getData - clib.libname.getData Representation of C++ function getData.
clib.libname.getData(s) Input Arguments s 2 element vector clib.array.libname.DataRecord
Display the help text for the typeclib.array.libname.DataRecord
. The type is a C++ array with elements of type clib.libname.DataRecord
.
help clib.array.libname.DataRecord
clib.array.libname.DataRecord C++ array with elements of type clib.libname.DataRecord.
Display the help text for the structure DataRecord
.
help clib.libname.DataRecord
DataRecord - clib.libname.DataRecord Representation of C++ class DataRecord.
struct with fields:
ID 5 element vector char
amount single
x double
Create a two-element MATLAB struct array with fields ID
,amount
, and x
.
s.ID = 'abcde'; s.amount = single(1000); s.x = 5; s(2).ID = 'vwxyz'; s(2).amount = single(1000); s(2).x = 5;
Convert the structure to a C++ array of typeclib.libname.DataRecord
.
sarr = clibConvertArray("clib.libname.DataRecord",s)
Call getData
.
clib.libname.getData(sarr)
In this example, the function parameter is input only, meaning the function does not modify the input. You can directly call getData
with the MATLAB structure array s
. MATLAB converts the array to a C++ struct
of typeclib.array.libname.DataRecord
.
Get the updated struct array back into MATLAB.
If the function modifies the input value, you must call clibConvertArray to convert the MATLAB struct array to a clib.array
object. Then, when you call the function with the clib.array
object, the function modifies the clib.array
object in place.
Use nullptr
in Pointer Fields. To assign nullptr
to a C++ struct
pointer data member, assign []
to a field in the MATLAB structure. For example, this C++ code definesMyStruct
.
#include <stdint.h>
struct Inner { int i; };
struct MyStruct {
char *str; // Mltype = "string", shape = "nullTerminated"
int32_t *x; // Mltype = "clib.array.lib.Int32"
Inner *in1; // Mltype = "clib.lib.Inner"
};
Create a MATLAB object myStruct
with these fields:
myStruct.str = ''; myStruct.x = int32.empty; % Assign nullptr to a struct pointer data member myStruct.in1 = struct([]); % Alternative nullptr assignment myStruct.in1 = struct.empty; obj = clib.lib.MyStruct(myStruct)
obj = MyStruct with properties:
str: [0×0 string]
x: [1×1 clib.array.lib.Int]
in1: [1×1 clib.lib.Inner]
You can convert this C++ struct
with pointer fields set tonullptr
to a MATLAB structure mlStruct
using thestruct
method.
mlStruct = struct with fields: str: '' x: [] in1: [1×1 struct]
Pass Fixed-Sized Array Parameter
If the parameter is a fixed-sized array, then the number of dimensions and the type of the elements of a passed array must match those of the expected parameter. For example, this function takes a fixed-sized array of typedouble
as input.
Display the help text from MATLAB.
fcn - clib.libname.fcn Representation of C++ function fcn.
clib.libname.fcn(arr) Input Arguments arr 3 element vector clib.array.libname.Double
Then call the function with a clib array of the required size and type.
arr3 = clibArray("clib.libname.Double",3); clib.libname.fcn(arr3);
Pass Parameter by Reference
You can pass a clib array to a C++ function that modifies the input data and returns the data to MATLAB. Then convert the data from the clib array to a MATLAB array using one of the methods listed in MATLAB C++ Object Array Methods. For example, these functions populate C++ arrays with data of typeint32_t
and char
.
#include #include
void getData(std::vector& arr) { int32_t data [] = {2, 4, 5}; arr.clear(); for (auto c : data) { arr.push_back(c); } } void getData(std::vector& arr) { char data [] = {'M', 'A', 'T', 'L', 'A', 'B', '\0'}; arr.clear(); for (auto c : data) { arr.push_back(c); } }
Call the getData
function to populate a numeric clib array of type int32_t
and convert it to a MATLABint32
array.
narr = clib.array.libname.Int(3); clib.libname.getData(narr) int32(narr)
ans = 1×3 int32 row vector
2 4 5
Now call the getData
function to populate a character array and convert it for use in MATLAB.
carr = clib.array.libname.Char(1); clib.libname.getData(carr); char(carr.int8)
Pass const
and Non-const
Parameters
A const
parameter can take a non-const
object, but a non-const
parameter cannot take aconst
object. For example, this C++ class has functions that create const
and non-const
objects and methods that take const
and non-const
inputs.
class MyClass { public: int m_value; MyClass():m_value(0) {} void nonConstMethod() {} int constMethod() const { return m_value; } } classObj;
MyClass& funcNonConstObj() { return classObj; }
const MyClass& funcConstObj() { return classObj; }
Display the help text from MATLAB.
help clib.libname.funcConstObj
funcConstObj - clib.libname.funcConstObj Representation of C++ function funcConstObj.
RetVal = clib.libname.funcConstObj Output Arguments RetVal read-only clib.libname.MyClass
help clib.libname.funcNonConstObj
funcNonConstObj - clib.libname.funcNonConstObj Representation of C++ function funcNonConstObj.
RetVal = clib.libname.funcNonConstObj Output Arguments RetVal clib.libname.MyClass
Create MyClass
objects obj1
andobj2
.
obj1 = clib.libname.funcConstObj; obj2 = clib.libname.funcNonConstObj;
Confirm that the const
object is read-only, and then pass it to its constMethod
and nonConstMethod
methods.
obj1.constMethod; obj1.nonConstMethod;
Error using clib.libname.MyClass/nonConstMethod Calling nonconst method 'nonConstMethod' of read-only object 'clib.libname.MyClass' not supported.
However, you can pass the non-const
object to both itsconstMethod
and nonConstMethod
methods.
obj2.constMethod; obj2.nonConstMethod;
Handle Updated Array Elements
If a C++ function updates the elements of an array parameter, then the function also updates the MATLAB clib array because the array is a MATLAB handle. For example, this function modifies the elements of the parameter doubleArr
.
void fcn(double * doubleArr, int size) { for(int i = 0; i < size; ++i) doubleArr[i] *= 2.0; }
To create interface libname
, edit thedefinelibname.m
definition file. Uncomment the statements defining fcn
and replace <SHAPE>
with"size"
. Then display the help text from MATLAB.
fcn - clib.libname.fcn Representation of C++ function fcn.
clib.libname.fcn(doubleArr) Input Arguments doubleArr vector clib.array.libname.Double
Call this function from MATLAB to update the array elements with their values multiplied by 2.
doubleArr = clibConvertArray("clib.libname.Double", [2 3 4]); clib.libname.fcn(doubleArr); doubleArr(3) % display element 3
MATLAB C++ Object Array Properties
MATLAB arrays created with clibArray
orclibConvertArray
have these properties.
Property | Type | Access | Description |
---|---|---|---|
Dimensions | double vector | Read-only | Dimensions of the C++ array. For example, [2 5 3] specifies a 2-by-5-by-3 array. |
Resizable | logical scalar | Read-only | true — You can add or remove elements.false — You cannot add or remove elements. |
MATLAB C++ Object Array Methods
MATLAB arrays created with clibArray
orclibConvertArray
have these methods.
Method | Syntax | Description |
---|---|---|
append | append([element]) | Add an optionally specified element to the end of the array.For a primitive MATLAB clib array, if you do not specify an input argument, then the method appends a zero value.For a class-type MATLAB clib array, if you do not specify an input argument, then the method appends an object created by the class-type default constructor. If the class-type default constructor is deleted, a run-time error occurs. |
removeLast | removeLast | Remove the last element of the array. If the MATLAB clib array is empty, a run-time error occurs. |
double | double | Convert to double precision. |
int8 | int8 | Convert to int8. |
uint8 | uint8 | Convert to uint8. |
int16 | int16 | Convert to int16. |
uint16 | uint16 | Convert to uint16. |
int32 | int32 | Convert to int32. |
uint32 | uint32 | Convert to uint32. |
int64 | int64 | Convert to int64. |
uint64 | uint64 | Convert to uint64. |
logical | logical | Convert to logical. |
struct (since R2024b) | struct | Convert to structure. |
Memory Management
The memory for MATLAB arrays created with clibArray
orclibConvertArray
is managed by MATLAB. You do not need to explicitly release the memory for clib arrays. For more information about releasing memory for C++ objects from MATLAB, see clibRelease.
See Also
clibArray | clibConvertArray | clibRelease | clibIsReadOnly