获取堆上对象的大小(以字节为单位) [英] Get the size (in bytes) of an object on the heap
问题描述
我知道您可以使用MemoryLayout<T>.size
来获取类型T
的大小.
I'm aware you can use MemoryLayout<T>.size
to get the size of a type T
.
例如:MemoryLayout<Int32>.size // 4
但是,对于类实例(对象),MemoryLayout<T>.size
返回对对象的引用的大小(在64位计算机上为8字节),而不是堆上实际对象的大小.
However, for class instances (objects), MemoryLayout<T>.size
returns the size of the reference to the object (8 bytes on 64 bit machines), not the size of the actual objects on the heap.
class ClassA { // Objects should be at least 8 bytes
let x: Int64 = 0
}
class ClassB {// Objects should be at least 16 bytes
let x: Int64 = 0
let y: Int64 = 0
}
MemoryLayout<ClassA>.size // 8
MemoryLayout<ClassB>.size // 8, as well :(
如何获取对象本身的大小?
How can I get the size of the objects themselves?
对于那些想知道的人,我并没有真正的需要,我只是在探索Swift及其与C的互操作性.
For those wondering, I have no real need for this, I'm just exploring around Swift and its interoperability with C.
推荐答案
在 Apple平台上的一个选项,因为Swift类是 class_getInstanceSize
,它为您提供了该类实例的大小(以字节为单位) ,包括任何填充.
One option on Apple platforms, because Swift classes are currently built on top of Objective-C classes there, would be to use the Obj-C runtime function class_getInstanceSize
, which gives you the size in bytes of an instance of the class, including any padding.
// on a 64-bit machine (1 word == 8 bytes)...
import Foundation
class C {}
print(class_getInstanceSize(C.self)) // 16 bytes metadata for empty class
// (isa ptr + ref count)
class C1 {
var i = 0
var i1 = 0
var b = false
}
print(class_getInstanceSize(C1.self)) // 40 bytes
// (16 metadata + 24 ivars, 8 for i + 8 for i1 + 1 for b + 7 padding)
这篇关于获取堆上对象的大小(以字节为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!