본문 바로가기
Dev.Mobile/iPhone

How to import C++ code into Swift

by Devkin 2014. 7. 6.

C Library를 포함하여 Objective-C Framework 및 Objective-C 로 작성된 사용자 코드는 Swift에서 직접 import 가능하다. 반면, Apple Document에 기술된 바에 의하면 C++ 코드의 경우는 직접 import가 불가하고 Objective-C 또는 C Wrapper를 생성하여 사용해야 한다.

You cannot import C++ code directly into Swift. Instead, create an Objective-C or C wrapper for C++ code.

Import Objective-C From Swift

SwiftHeader가 없는 단일 파일로 아래 그림에서 보듯이 Framework이 아닌 일반적인 App 프로젝트에서는 bridging header 를 통해 Objective-C 코드를 참조하게 된다.

Swift 프로젝트에서 Objective-C 파일을 추가하면 Mixed Swift and Objective-C target으로 판단하여 “YourProductName-Bridging-Header.h” 네이밍으로 bridging header 를 생성하게끔 한다.

생성된 header에 참조하고 싶은 class들을 import 하면 되는데, Swift 코드에서는 따로 코드 추가 없이 자동적으로 bridging header에 import된 class들을 참조하게 된다.

// MixedLang-bridging-header.h

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import "ObjCWrapper.h"

Import C++ From Objective-C Wrapper

C++ Class

// CppWrapped.h

#ifndef __CPP_WRAPPED_H__
#define __CPP_WRAPPED_H__

class CppWrapped
{
public:
    static void foo(int n);
};

#endif
// CppWrapped.cpp

#include <stdlib.h>
#include "CppWrapped.h"

void CppWrapped::foo(int n)
{
    bar(n);
}

Objective-C Wrapper Class

// ObjCWrapper.h

#import <Foundation/Foundation.h>

@interface ObjCWrapper : NSObject
+ (void) foo: (NSInteger) n;
@end
// ObjCWrapper.mm

#import "ObjCWrapper.h"
#import "CppWrapped.h"

@implementation ObjCWrapper
+ (void) foo: (NSInteger) n
{
    CppWrapped::foo( (int)n );
}
@end

Using The Class From Swift

앞서 말한바와 같이, bridging-header에 추가된 ObjCWrapper.h의 method는 Swift 코드에서 바로 사용 가능하다.

// main.swift

import Foundation

let n : Int(arc4random_uniform(7))

ObjCWrapper.foo(n)

REFERENCE

반응형

댓글