混合使用Objective-C,C++和Objective-C++
之前有段时间,我参与了一项使用了C++库的Objective-C项目。写了一篇关于混编的文章,结果却出乎意料的成为Google搜索中关于Objective-C++的最靠前的结果之一。
后来,Apple将基于LLVM的clang做为主选编译器。其作用之一就是可以保证Objective-C的演化,而GCC的进化却太慢了。之前文章就不太适用了,而且在这个过程,我也收到了一些回馈,这些都促使我写了这篇文章。
回顾一下
简言之,如果你有一些C++代码或库,你想在Objective-C项目使用它,这就是我们要研究的问题。 通常,C++代码中会定义你要使用的一些类(class), 你可以简单的把.m文件扩展名改为.mm就可以改为Objective-C++编译,然后就可以很容易地混合使用C++和Objective-C的代码。这是一个简单的做法,但两个世界确实很不一样,如此这样的深度混合有时会变地很棘手。
你可能会想使用等价的Objective-C类型和函数将C++代码封装(wrap)起来。比方说,你有一个名为CppObject的C++类(CppObject.h):
#include <string>class CppObject{public: void ExampleMethod(const std::string& str); // constructor, destructor, other members, etc.};#import <Foundation/Foundation.h>#import "CppObject.h"@interface ObjcObject : NSObject { CppObject wrapped;}- (void)exampleMethodWithString:(NSString*)str;// other wrapped methods and properties@end
然后在ObjcObject.mm中实现这些方法。不过,此时会在两个头文件(ObjcObject.h&CppObject.h)中得到一个预处理和编译错误。问题出在#include和#import上。对于预处理器而言,它只做文本的替换操作。所以#include和#import本质上就是递归地复制和粘贴引用文件的内容。这个例子中,使用#import "ObjcObject.h"等价于插入如下代码:
// [首先是大量Foundation/Foundation.h中的代码]// [无法包含<string>],因为它仅存在于C++模式的include path中class CppObject{public: void ExampleMethod(const std::string& str); // constructor, destructor, other members, etc.};@interface ObjcObject : NSObject { CppObject wrapped;}- (void)exampleMethodWithString:(NSString*)str;// other wrapped methods and properties@end#import "ObjcObject.h"@interface ObjcObject () // note the empty parentheses- (void)methodWeDontWantInTheHeaderFile;@end@implementation ObjcObject// etc.
GCC也支持这个操作。不过clang还支持添加ivar块,也就是你还可以声明C++类型的实例变量,既可以在class extension中,也可以在@implementation开始的位置。本例中的ObjcObject.h可以被精简为:
#import <Foundation/Foundation.h>@interface ObjcObject : NSObject- (void)exampleMethodWithString:(NSString*)str;// other wrapped methods and properties@end
去掉的部分都移到实现文件的class extension中 (ObjcObject.mm):
#import "ObjcObject.h"#import "CppObject.h"@interface ObjcObject () { CppObject wrapped;}@end@implementation ObjcObject- (void)exampleMethodWithString:(NSString*)str{ // NOTE: str为nil会建立一个空字串,而不是引用一个指向UTF8String空指针. std::string cpp_str([str UTF8String], [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); wrapped.ExampleMethod(cpp_str);}
如果我们不需要interface extension来声明额外的属性和方法,ivar块仍然可以放在@implementation开始位置:
#import "ObjcObject.h"#import "CppObject.h"@implementation ObjcObject { CppObject wrapped;}- (void)exampleMethodWithString:(NSString*)str{ // NOTE: str为nil会建立一个空字串,而不是引用一个指向UTF8String空指针. std::string cpp_str([str UTF8String], [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); wrapped.ExampleMethod(cpp_str);}定义的CppObject实例wrapped在ObjcObject创建时,CppObject的缺省建构函数会被调用,而在ObjcObject被调用dealloc析构时,ObjcObject的析构函数也会被调用。如果ObjcObject没有提供缺省的建构函数,编译就会失败。@interface ObjcObject () { CppObject* wrapped; // 指针!会在alloc时初始为NULL.}@end@implementation ObjcObject- (id)initWithSize:(int)size{ self = [super init]; if (self) { wrapped = new CppObject(size); if (!wrapped) self = nil; } return self;}//...
如果是使用C++异常, 也可以使用 try {...} catch {...}把创建过程封装起来. 相应地,还要显式地释放封闭对象:
- (void)dealloc{ delete wrapped; [super dealloc]; // 如果使用了ARC,这句就要略去}
作者接着提到了另一个方法,显示分配一块内存,然后在它的基础上调用new来创建对象。首先声明char wrapped_mem[sizeof(CppObject)]; 再使用wrapped = new(wrapped_mem) CppObject();创建了实例wrapped。释放时if (wrapped) wrapped->~CppObject(); 这样虽然可行,但不建议使用。
#import <Foundation/Foundation.h>@interface ABCWidget- (void)init;- (void)reticulate;// etc.@end
这样的类定义在Objective-C++中是没有问题的,但在纯C++的代码是不允许的:
#import "ABCWidget.h"namespace abc{ class Widget { ABCWidget* wrapped; public: Widget(); ~Widget(); void Reticulate(); };}
一个纯粹的C++编译器在Foundation.h中的代码和ABCWidget声明位置出错。
namespace abc{ struct WidgetImpl; class Widget { WidgetImpl* impl; public: Widget(); ~Widget(); void Reticulate(); };}
然后在Widget.mm中:
#include "Widget.hpp"#import "ABCWidget.h"namespace abc{ struct WidgetImpl { ABCWidget* wrapped; }; Widget::Widget() : impl(new WidgetImpl) { impl->wrapped = [[ABCWidget alloc] init]; } Widget::~Widget() { if (impl) [impl->wrapped release]; delete impl; } void Widget::Reticulate() { [impl->wrapped reticulate]; }} #include <objc/objc-runtime.h>namespace abc{ class Widget { id /* ABCWidget* */ wrapped; public: Widget(); ~Widget(); void Reticulate(); };}
不建议向id对象直接发送消息。这样你会失去很多编译器的检查机制,特别是对于不同类中有着相同selector名字的不同方法时。所以:
#include "Widget.hpp"#import "ABCWidget.h"namespace abc{ Widget::Widget() : wrapped([[ABCWidget alloc] init]) { } Widget::~Widget() { [(ABCWidget*)impl release]; } void Widget::Reticulate() { [(ABCWidget*)impl reticulate]; }}
像这样的类型转换很容易在代码中隐藏错误,再尝试一个更好的方式。在头文件中:
#ifdef __OBJC__@class ABCWidget;#elsetypedef struct objc_object ABCWidget;#endifnamespace abc{ class Widget { ABCWidget* wrapped; public: Widget(); ~Widget(); void Reticulate(); };}
如果这个头文件被一个mm文件引用,编译器可以充分识别到正确的类。 如果是在纯C++模式中引用,ABCWidget*是一个等价的id类型:定义为typedef struct objc_object* id; 。 #ifdef块还可以被进一步放到一个可重用的宏中:
#ifdef __OBJC__#define OBJC_CLASS(name) @class name#else#define OBJC_CLASS(name) typedef struct objc_object name#endif