출처 : https://jk2b.tistory.com/5
swift에서 C++ 소스를 바로 사용할 수 없기 때문에 c++ 소스를 objective c 소스로 wrapping 해주어야 한다. 이때 wrapping 된 소스를 objective c++ 라고 한다.
#include <stdio.h>
#include <iostream>
class MyCpp{
public:
MyCpp();
~MyCpp();
public:
void sayHello();
};
#include "MyCpp.hpp"
MyCpp::MyCpp(){}
MyCpp::~MyCpp(){}
void MyCpp::sayHello()
{
std::cout<<"Hello world!!"<<std::endl;
}
다음 과같은 c++ 소스를 swift 에서 사용하기 위해서는
#import <Foundation/Foundation.h>
@interface CWrapper: NSObject
- (void) helloWorld;
@end
*.mm 작성하기
#import "CWrapper.h"
#include "MyCpp.hpp"
@interface CWrapper()
@property MyCpp *cppItem;
@end
@implementation CWrapper
-(instancetype) init{
self = [super init];
self.cppItem = new MyCpp();
return self;
}
-(void) helloWorld{
self.cppItem->sayHello();
}
@end
import UIKit
class ViewController: UIViewController {
let wrapper = CWrapper()
override func viewDidLoad() {
super.viewDidLoad()
self.wrapper.helloWorld()
// Do any additional setup after loading the view.
}
}