Main Content

迭代 lib.pointer 对象

从 lib.pointer 对象创建元胞数组

此示例说明如何从 getListOfStrings 函数的输出创建 MATLAB® 字符向量元胞数组 mlStringArray

加载 shrlibsample 库。

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

调用 getListOfStrings 函数以创建一个字符向量数组。该函数返回指向该数组的指针。

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

创建索引变量以循环访问数组。对函数返回的数组使用 ptrindex,对 MATLAB 数组使用 index

ptrindex = ptr;
index = 1;

创建字符向量元胞数组 mlStringArray。将 getListOfStrings 的输出复制到该元胞数组。

% 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

查看元胞数组的内容。

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

对结构体数组执行指针算术

此示例说明如何使用指针算术来访问结构体的元素。该示例基于 shrlibsample.h 头文件中的 c_struct 定义创建一个 MATLAB 结构体。

加载该定义。

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

创建 MATLAB 结构体。

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

创建指向该结构体的指针。

sptr = libpointer('c_struct',s);

读取第一个元素的值。

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

通过递增指针来读取下一个元素的值。

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