OC類型的代碼削罩,底層實現(xiàn)都是C/C++語言,可以說糊昙,OC語言就是對C/C++語言的封裝辛掠,比如,任何OC對象释牺,添加__bridge const void *
修飾萝衩,都可以轉變?yōu)関oid指針類型。
資料
使用Clang可以將OC代碼没咙,重寫為C++代碼猩谊。
xcrun 是 Command Line Tools 中的一員。它的作用類似 RubyGem 里的 Bundle 镜撩,用于控制執(zhí)行環(huán)境预柒。
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc oc文件 -o 輸出的cpp文件
新建一個Xcode Project,選擇macOS->Application->Command Line Tool,打開工程袁梗,在main.m文件中改為如下代碼
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSObject *obj = [[NSObject alloc] init];
}
return 0;
}
打開終端宜鸯,cd到main.m目錄,根據(jù)上面命令遮怜,輸入
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main.cpp
如有報錯淋袖,請去下文錯誤
處查找解決辦法。
如無報錯锯梁,可在文件夾中即碗,找到main.cpp文件焰情,打開,將光標移動到最后剥懒,可見以下C++代碼内舟。
/// An opaque type that represents an Objective-C class.
typedef struct objc_class *Class;
/// Represents an instance of a class.
struct objc_object {
Class _Nonnull isa;
};
typedef struct objc_object NSObject;
int main(int argc, const char * argv[]) {
/* @autoreleasepool */ { __AtAutoreleasePool __autoreleasepool;
NSObject *obj = ((NSObject *(*)(id, SEL))(void *)objc_msgSend)((id)((NSObject *(*)(id, SEL))(void *)objc_msgSend)((id)objc_getClass("NSObject"), sel_registerName("alloc")), sel_registerName("init"));
}
return 0;
}
由此可見,一個NSObject對象初橘,它的底層验游,其實是一個struct, 因此NSObject *其實是一個結構體指針,所以任何OC對象都可以使用(__bridge const void *)
將其轉化為C語言指針保檐。
指針類型占據(jù)的存儲空間取決于編譯器和操作系統(tǒng)的實現(xiàn)耕蝉。在一些32位系統(tǒng)中,一個指針變量通常占據(jù)4個字節(jié)的空間夜只,而在一些64位系統(tǒng)中垒在,則需要8個字節(jié)的空間。這是因為指針是內存地址的數(shù)字表示扔亥,在32位系統(tǒng)中场躯,一個數(shù)字數(shù)字占據(jù)4個字節(jié)的空間,而在64位系統(tǒng)中則需要8個字節(jié)旅挤。
而在64位機器中推盛,指針占用8個字節(jié)。objc_object中的isa谦铃,其實是一個class指針,因此榔昔,一個NSObject驹闰,只需要8個字節(jié)就可以存下。
驗證
objc/runtime.h中撒会,由這樣一個方法嘹朗,返回一個類的實例的大小
/**
* Returns the size of instances of a class.
*
* @param cls A class object.
*
* @return The size in bytes of instances of the class \e cls, or \c 0 if \e cls is \c Nil.
*/
OBJC_EXPORT size_t
class_getInstanceSize(Class _Nullable cls)
OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);
我們知道,在malloc/malloc.h
中诵肛,有個malloc_size方法
extern size_t malloc_size(const void *ptr);
/* Returns size of given ptr, including any padding inserted by the allocator */
返回給定指針的大小屹培,包括分配器插入的填充量。
在 main.m中怔檩,輸入
NSLog(@"%lu,%zu", class_getInstanceSize([NSObject class]));
//輸出:8
NSLog(@"%lu", malloc_size((__bridge const void *)(obj)));
//輸出:16
出現(xiàn)兩種結果褪秀。我們查看Objc4的源碼,下載后打開工程,可查到如下源碼:
size_t class_getInstanceSize(Class cls)
{
if (!cls) return 0;
return cls->alignedInstanceSize();
}
// Class's ivar size rounded up to a pointer-size boundary.
uint32_t alignedInstanceSize() const {
return word_align(unalignedInstanceSize());
}
發(fā)現(xiàn)class_getInstanceSize實際上返回的是類的成員變量的大小薛训,并且按照指針大忻铰稹(8個字節(jié))取整。
因此乙埃,我們應當用malloc_size返回的結果闸英。這個結果才是系統(tǒng)為obj分配的大小锯岖。
經(jīng)過閱讀libmalloc的源碼,發(fā)現(xiàn)malloc其實是按照16個字節(jié)對齊的甫何,因此出吹,一個對象的內存大小一定是16的倍數(shù)。
Swift
import Foundation
var obj = NSObject()
print(MemoryLayout.size(ofValue: obj))
print(class_getInstanceSize(NSObject.self))
let objRawPtr = Unmanaged.passUnretained(obj as AnyObject).toOpaque()
print(malloc_size(objRawPtr))
//輸出:
//8
//8
//16
同樣辙喂,Swift的底層也是C++代碼捶牢。將對象轉為指針,使用malloc_size
也能得到Swift對象的大小加派。
錯誤
1.xcrun error
xcrun: error: SDK "iphoneos" cannot be located
xcrun: error: Failed to open property list '/Users/tongyulong/Documents/Test/test01/test01/iphoneos/SDKSettings.plist'
main.m:8:9: fatal error: 'Foundation/Foundation.h' file not found
#import <Foundation/Foundation.h>
^~~~~~~~~~~~~~~~~~~~~~~~~
main.m:8:9: note: did not find header 'Foundation.h' in framework 'Foundation' (loaded from '/System/Library/Frameworks')
1 error generated.
一般情況叫确,出現(xiàn)上訴錯誤,就是sdk路徑錯誤芍锦。
在命令行輸入
xcodebuild -showsdks
如果出現(xiàn)
xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance
輸入以下命令解決竹勉。
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer/
然后繼續(xù)執(zhí)行xrcun