전글에서 XCode상에서 C++모듈을 사용하는 방법을 알아보았다.
이번엔 단순이 wrapper클래스를 만들어 C++모듈을 의식하지 않고 Objective-C에서 사용할 수 있도록 wrapper메소드를 만들어보자.
아래와 같은 C++ 클래스 라이브러리가 있다고 치자.
Wrapped.hpp
#ifndef __WRAPPED_H__
#define __WRAPPED_H__
class CWrapped
{
public:
CWrapped(int param1, int param2);
unsigned int doSomething();
}
#endif
Wrapped.cpp
#include "Wrapped.hpp"
CWrapped::CWrapped(int param1, int param2)
{
// do something
}
unsigned int CWrapped::doSomething()
{
// do something
return 0;
}
이것을Objective-C++의 문법으로 wrap해야 하지만 이 wrap를 Objective-C에서 이용하기 위해서는 조금 해더파일의 C++의 문법을 사용하지 않는 단순한 Objective-C 문법으로 하지 않으면 안된다.
특히 class키워드를 사용하지 않기위해 Objective-C++ 의 헤더파일은 #ifdef 을 사용한다.
Wrapper.h (헤더파일)
#import <Foundation/NSObject.h>
// declare CWrapped class for .mm (Obj-C++) files
#ifdef __cplusplus
class CWrapped;
#endif
// declare CWrapped class for .m (Obj-C) files (do not use the "class" keyword.)
#ifdef __OBJC__
#ifndef __cplusplus
typedef void CWrapped;
#endif
#endif
@interface Wrapper : NSObject {
CWrapped* mWrapped;
}
- (id)init:(int)param param2:(int)param2;
- (unsigned int)doSomething;
@end
Wrapper.mm (구현부분)
#import "Wrapper.h"
@implementation Wrapper
- (id)init:(int)param1 param2:(int)param2
{
if (self = [super init]) {
mWrapped = new CWrapped(param1, param2);
}
return self;
}
- (void)dealloc
{
delete mWrapped;
[super dealloc];
}
- (unsigned int)doSomething
{
return mWrapped->doSomething();
}
@end
Objective-C에서는 아래와 같이 이용할 수 있다.
main.m
#import "Wrapper.h" // Objective-C 에서 보는 class CWrapped 가 아닌 typedef void CWrapped 이기때문에 컴파일이 됨.
int main(int argc, char **argv)
{
Wrapper *wrapper = [[Wrapper alloc] init:10 param2:10];
unsigned int result = [wrapper doSomething];
[wrapper dealloc];
}
위의 코드는 실제로 돌려보지는 않았다. 아래는 참고사이트
http://note.sonots.com/Comp/CompLang/Cocoa/ObjectiveCWrapper.html
이 코드를 베이스로 Wrapper클래스를 만들기 했는데 귀찮아서 올리기는 그렇고..
위의 코드를 참고로 기본틀을 만들고 필요한 것은 적당히 스택플로우를 참고하면 원하는 Wrapper클래스를 만들 수 있을것이다.
나의 경우는 unsigned char*를 NSData로 형변환해야 하는등에 귀찮은 작업이 있었지만 스택플로우의 힘으로 모두 클리어.
생각대로 잘 동작한다.
끝.
'코딩(プログラミング)' 카테고리의 다른 글
블럭코드에서의 ARC Retain Cycle Error 해결방법 (0) | 2013.07.23 |
---|---|
NSError카테고리를 이용한 자체에러정의하기 (0) | 2013.07.19 |
cpp 파일(C++)의 wrapper클래스 만들어 사용하기(2) (0) | 2013.07.18 |
XCode(Objective-C)상에서 cpp 파일(C++) 사용하기(1) (2) | 2013.07.11 |
iPhone에서 DropBox, SkyDrive, GoogleDrive API 연동하기. (3) | 2013.07.10 |
XCode에서 로컬Git 생성하기 (0) | 2013.04.14 |
댓글을 달아 주세요