有時候,出於性能或可移植性的考慮,需要在iOS項目中使用到C++。
假設我們用C++寫了下面的People類:
[cpp]
//
// People.h
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#ifndef __MixedWithCppDemo__People__
#define __MixedWithCppDemo__People__
#include <iostream>
class People
{
public:
void say(const char *words);
};
#endif /* defined(__MixedWithCppDemo__People__) */
[cpp] view plaincopy
//
// People.cpp
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#include "People.h"
void People::say(const char *words)
{
std::cout << words << std::endl;
}
然後,我們用Objective-C封裝一下,這時候文件後綴需要為.mm,以告訴編譯器這是和C++混編的代碼:
[cpp]
//
// PeopleWrapper.h
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#import <Foundation/Foundation.h>
#include "People.h"
@interface PeopleWrapper : NSObject
{
People *people;
}
- (void)say:(NSString *)words;
@end
[cpp] view plaincopy
//
// PeopleWrapper.mm
// MixedWithCppDemo
//
// Created by Jason Lee on 12-8-18.
// Copyright (c) 2012年 Jason Lee. All rights reserved.
//
#import "PeopleWrapper.h"
@implementation PeopleWrapper
- (void)say:(NSString *)words
{
people->say([words UTF8String]);
}
@end
最後,我們需要在ViewController.m文件中使用PeopleWrapper:
[cpp]
PeopleWrapper *people = [[PeopleWrapper alloc] init];
[people say:@"Hello, Cpp.\n"];
[people release], people = nil;
結果發現編譯通不過,提示“iostream file not found”之類的錯誤。
這是由於ViewController.m實際上也用到了C++代碼,同樣需要改後綴名為.mm。
修改後綴名後編譯通過,可以看到輸出“
Hello, Cpp.
”。