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