Main Content

Iterate Throughlib.pointerObject

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 thegetListOfStringsfunction.

Load theshrlibsamplelibrary.

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

Call thegetListOfStringsfunction 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. Useptrindexfor the array returned by the function andindexfor the MATLAB array.

ptrindex = ptr; index = 1;

Create the cell array of character vectorsmlStringArray. Copy the output ofgetListOfStringsto the cell array.

% read until end of list (NULL)whileischar(ptrindex.value{1}) mlStringArray{index} = ptrindex.value{1};% increment pointerptrindex = ptrindex + 1;% increment array indexindex = 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 thec_structdefinition in theshrlibsample.hheader file.

Load the definition.

ifnot(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});

创建一个指针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