Documentation Center

  • Trial Software
  • Product Updates

Iterate Through an Array

Create Cell Array from lib.pointer Object

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

The getListOfStrings function creates an array of strings and returns a pointer to the array.

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

Call the function.

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

lib.pointer

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

ptrindex = ptr;
index = 1; 

Create the cell array of strings, mlStringArray:

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

To view the contents of the cell array, type:

mlStringArray
mlStringArray = 
    'String 1'    'String Two'     ''    '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;

To read the values of the next element, increment the pointer.

sptr = sptr + 1;
v2 = sptr.Value;
Was this topic helpful?