Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent in Swift of offsetof(struct, member) in C?

Here's a struct in Swift:

struct A {
    var x
    var y
    var z
}

What should I do to get the offset of y in the struct A, just like offsetof(A, y) in C?

Thanks :)

like image 806
Lizhen Hu Avatar asked Dec 11 '22 07:12

Lizhen Hu


1 Answers

MemoryLayout.offset(of:) was added in Swift 4.2, with the implementation of

  • SE-0210 Add an offset(of:) method to MemoryLayout

Example:

struct A {
    var x: Int8
    var y: Int16
    var z: Int64
}

MemoryLayout.offset(of: \A.x) // 0
MemoryLayout.offset(of: \A.y) // 2
MemoryLayout.offset(of: \A.z) // 8

Remark: This should work as well, but (as of Swift 4.2) does not compile (bug SR-8335):

MemoryLayout<A>.offset(of: \.y)
// error: Expression type 'Int?' is ambiguous without more context
like image 88
Martin R Avatar answered Mar 14 '23 21:03

Martin R