Main Content

MATLAB Object for C++ Arrays

MATLAB® provides the clib.array interface to wrap C++ native arrays and std::vector types. The term clib array refers to the MATLAB representation of these C++ types.

A MATLAB clib array is defined only when the corresponding C++ native array or std::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 MATLAB clibArray 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 is clib.array.libname.myclass. To access an element of myclassArray, use MATLAB indexing. For example, access the first element.

e = myclassArray(1)

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 in C++ 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 five clib.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<T> String Types table for element type information. For example, if the C++ type is std::vector<std::string>, then the MATLAB element type is clib.libname.std.String. Create an array with five clib.libname.std.String elements.

myStringArray = clib.array.libname.std.String(5)

Treat C++ Native Arrays of Fundamental Type as MATLAB Fundamental Types

By default, MATLAB represents C++ native arrays of fundamental types with the MATLAB clib.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 argument set to false. For more information, see clibgen.generateLibraryDefinition.

Note

Saving C++ objects into a MAT-file is not supported.

Note

You cannot create an array of C++ objects using square brackets.

Call C++ Function with clib.array Parameter

You can create a MATLAB variable to pass as a parameter for specific C++ types. These examples show how to pass a clib parameter directly, by reference, as a fixed-size array, to update array elements, and as const and non-const objects. The code assumes you build an interface named libname.

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 an std::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 type double.

void fcn(std::vector<double> doubleVec);

Display the function signature from MATLAB.

help clib.libname.fcn
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
ans =
     2     3
clib.libname.fcn(arr2d)
Error using clib.libname.fcn
No method 'clib.libname.fcn' with matching signature found.

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 type double.

void fcn(double arr[3]);

Display the function signature from MATLAB.

help clib.libname.fcn
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 by Reference Parameter

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 type int32_t and char.

#include <cstdint>
#include <vector>

void getData(std::vector<int32_t>& arr) {
   int32_t data [] = {2, 4, 5};
   arr.clear();
   for (auto c : data) {
       arr.push_back(c);
   }
}
void getData(std::vector<char>& 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 MATLAB int32 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)
ans = 'MATLAB '

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 the definelibname.m definition file. Uncomment the statements defining fcn and replace <SHAPE> with "size". Display the function signature from MATLAB.

help clib.libname.fcn
fcn -  clib.libname.fcn Representation of C++ function fcn.

  clib.libname.fcn(doubleArr)
    Input Arguments
      doubleArr      vector clib.array.libname.Double  

Then call this function from MATLAB to update the array elements with double their values.

doubleArr = clibConvertArray("clib.libname.Double", [2 3 4]); 
clib.libname.fcn(doubleArr); 
doubleArr(3) % display element 3
ans = 
     8

const and Non-const Parameters

A const parameter can take a non-const object, but a non-const parameter cannot take a const 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 function signatures 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 and obj2.

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.

clibIsReadOnly(obj1)
ans = 
   1
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 of its constMethod and nonConstMethod methods.

clibIsReadOnly(obj2)
ans = 
   0
obj2.constMethod;
obj2.nonConstMethod;

Convert MATLAB Array to C++ Array Object

You can use an existing MATLAB array as a C++ array object. Call the clibConvertArray function. 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'

MATLAB C++ Object Array Properties

MATLAB arrays created with clibArray or clibConvertArray have these properties.

Property

TypeAccess

Description

Dimensions

double vectorRead-only

C++ dimensions of the array. For example, [2 5 3] specifies a 2-by-5-by-3 array.

Resizable

logical scalarRead-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 or clibConvertArray 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 there is no input argument, then a zero value is appended.

For a class-type MATLAB clib array, if there is no input argument, then the class-type default constructor is appended. 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.

Memory Management

The memory for MATLAB arrays created with clibArray or clibConvertArray is owned and 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

| | |

Related Topics