Main Content

Iterate Through lib.pointer Object

Create Cell Array from lib.pointer Object

This example shows how to create a MATLAB® cell array of character vectors, mlStringArray, from the output of the getListOfStrings function.

Load the shrlibsample library.

if not(libisloaded('shrlibsample'))
    addpath(fullfile(matlabroot,'extern','examples','shrlib'))
    loadlibrary('shrlibsample')
end

Call the getListOfStrings function to create an array of character vectors. The function returns a pointer to the array.

ptr = calllib('shrlibsample','getListOfStrings');
class(ptr)
ans = 
'lib.pointer'

Create indexing variables to iterate through the arrays. Use ptrindex for the array returned by the function and index for the MATLAB array.

ptrindex = ptr;
index = 1;

Create the cell array of character vectors mlStringArray. Copy the output of getListOfStrings to the cell array.

% read until end of list (NULL)
while ischar(ptrindex.value{1}) 
    mlStringArray{index} = ptrindex.value{1};
    % increment pointer 
    ptrindex = ptrindex + 1; 
    % increment array index
    index = index + 1; 
end

View the contents of the cell array.

mlStringArray
mlStringArray = 1x4 cell
    {'String 1'}    {'String Two'}    {0x0 char}    {'Last string'}

Perform Pointer Arithmetic on Structure Array

This example shows how to use pointer arithmetic to access elements of a structure. The example creates a MATLAB structure, based on the c_struct definition in the shrlibsample.h header file.

Load the definition.

if not(libisloaded('shrlibsample'))
    addpath(fullfile(matlabroot,'extern','examples','shrlib'))
    loadlibrary('shrlibsample')
end

Create the MATLAB structure.

s = struct('p1',{1,2,3},'p2',{1.1,2.2,3.3},'p3',{0});

Create a pointer to the structure.

sptr = libpointer('c_struct',s);

Read the values of the first element.

v1 = sptr.Value
v1 = struct with fields:
    p1: 1
    p2: 1
    p3: 0

Read the values of the next element by incrementing the pointer.

sptr = sptr + 1;
v2 = sptr.Value
v2 = struct with fields:
    p1: 2
    p2: 2
    p3: 0