iOS/Swift

[Swift] OpaquePointer vs UnsafePointer

CommitGuy 2024. 7. 4. 09:00

Swift에서 Object-C, C, CPP 코드를 써야하는 경우 OpaquePointer와 UnsafePointer를 자주 볼 수 있다. 둘다 별 생각없이 쓰거나 읽었는데 이 둘의 차이를 확인해보자

 

결론부터 말하면 이둘의 차이는 header 파일에서 찾을 수 있다

 

header 파일안에 struct가 완전히 정의되어 있다면 UnsafePointer를 Swift에서 사용가능하며 포인터를 dereference 할 수 있고 .pointee를 호출해 안에있는 content를 볼 수 있다.

 

// sample.h
typedef struct Person person;

struct Person
{
    int age;
    char* first_name;
}

void ShowInformation(Person*)

 

void ShowInformation(Person*) 을 Swift에서 사용할때 func ShowInformation(:_UnsafeMutablePointer<Person>!) 으로 변환되게 된다

 

반대로 OpaquePointer는 header에 struct가 불완전하게 정의되어 있다면 이때 사용하게 된다

// sample.h

typedef struct Person person;

void ShowInformation(Person*);
// sample.m

struct Person
{
    int age;
    char* first_name;
}

이럴 경우 Person은 header에는 있지만 불투명한(opaque) 혹은 불완전(imcompatible)한데 이럴경우 opaquePointer를 사용한다

 

void ShowInformation(Person*)의 경우 func ShowInformation(_:OpaquePointer!)로 변환된다

'iOS > Swift' 카테고리의 다른 글

[Swift] Actor 란?  (0) 2024.07.03