Main Content

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.

Display Help for Interface

Suppose that you have an interface with the overloaded function getData. To run this example, follow the instructions in Build Interface for Pass by Reference Example to generate a MATLAB interface named libByRef.

When you display help for libByRef, you see that it contains two functions named getData.

help clib.libByRef
Functions contained in clib.libByRef:
getData                        -  clib.libByRef.getData Representation of C++ function getData.

getData                        -  clib.libByRef.getData Representation of C++ function getData.

To see the input argument types, display help for the getData functions.

help clib.libByRef.getData
getData -  clib.libByRef.getData Representation of C++ function getData.

  clib.libByRef.getData(arr)
    Input Arguments
      arr            vector clib.array.libByRef.Int  

 clib.libByRef.getData Representation of C++ function getData.

  clib.libByRef.getData(arr)
    Input Arguments
      arr            vector clib.array.libByRef.Char  

The function accepts a vector of type clib.array.libByRef.Int or clib.array.libByRef.Char.

Use in MATLAB

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.libByRef.Int(3);
clib.libByRef.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.libByRef.Char(1);
clib.libByRef.getData(carr); 
char(carr.int8)
ans = 'MATLAB '

Build Interface for Pass by Reference Example

This C++ header file defines functions that 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);
   }
}

To run the example, save this code in a header file named getData.hpp, then generate a MATLAB interface named libByRef following the instructions in Header-Only HPP File.

Library ArtifactsMATLAB Interface libnameMATLAB Help

Header file getData.hpp

clib.libByRef

>> help clib.libByRef