Main Content

Create MATLAB Data Array and Manage Memory from User-Managed Buffer

This example C++ code shows how to use the MATLAB® Data API to create a MATLAB data array (MDA) from an array that has been allocated by a third-party library, without copying the data. It also shows how to control the lifetime of the MDA by using a custom deleter.

To create the MDA, write this function createMDA. The inputs are the dimensions of the MDA to create and a pointer to the memory allocated by library lib. Assume that the function get_raw_data_pointer obtains the underlying raw data pointer from an array allocated by the library.

To control the lifetime of the array, define a buffer with the data, provide a deleter (customDeleterFcn of type buffer_deleter_t), then pass the buffer to createArrayFromBuffer.

#include "MatlabDataArray.hpp"
using namespace matlab::data;
/*
* createMDA: User function to create MATLAB data array (MDA)
* input 1: Dimension of the MDA to be created
* input 2: Pointer to memory allocated by 3p library "lib"
* output: MATLAB data array
* get_raw_data_pointer: Library function to get pointer to data
* customDeleterFcn: User-created deleter function
*/
Array createMDA(ArrayDimensions dims,
                std::shared_ptr<lib::DoubleArray> libArray) {
  ArrayFactory factory;
 
  // Create a buffer (type: buffer_ptr_t) that holds the user data and a custom deleter.
  buffer_ptr_t<double> customBuffer(libArray.get_raw_data_pointer(), customDeleterFcn);
  
  return factory.createArrayFromBuffer(std::move(dims),
    std::move(customBuffer));
}

For information about the buffer_ptr_t and buffer_deleter_t data types, see MATLAB Data API Types.

For a MEX file example, see Using a custom deleter in a buffer_ptr_t in ArrayFacto​ry::create​ArrayFromB​uffer.

See Also

Related Topics