Forked from misbell/gist:fa7ecd562a9b0d9c1237eed5e1a6d89e
Created
June 14, 2021 08:20
-
-
Save gatherheart/8c751bd1463d41c5bc0b8ebebb76be6c to your computer and use it in GitHub Desktop.
example Swift 3 withMemoryRebound
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
so A and B are structurally identical | |
C reverses the order of the 8 and 32 bit Ints | |
and D substitutes a string for the Int8 | |
then I try to read aaaa’s bits using B C and D overlays 😊 | |
C is printing the 8 bits of the A integer j and then the first 8 bits of integer k but somehow that still works out to one | |
when I hit D it doesn’t find a string so prints a blank | |
but the important point is: it doesn’t check anything, and doesn’t crash | |
so ‘undefined behavior’, as it should be | |
func newInSwift3 () { | |
class A { | |
var j: Int8 = 1 | |
var k: Int32 = 3 | |
} | |
class B { | |
var j: Int8 = 2 | |
var k: Int32 = 4 | |
} | |
class C { | |
var j: Int32 = 5 | |
var k: Int8 = 7 | |
} | |
class D { | |
var j: String = "hello" | |
var k: Int32 = 9 | |
} | |
var aa = A() | |
let bb = B() | |
let cc = C() | |
let dd = D() | |
var unsfmut : UnsafeMutablePointer<A> = UnsafeMutablePointer<A>.allocate(capacity: 1) | |
unsfmut.initialize(to: aa) | |
let aaa = UnsafePointer<A>(unsfmut) | |
var aaaa : A = A() | |
aaaa = unsfmut.pointee | |
aaaa = aaa.pointee | |
print ("j is \(aaaa.j)") | |
withUnsafePointer(to: &aa) { (ptr: UnsafePointer<A>) in | |
let vptr = UnsafeRawPointer(ptr) | |
ptr.withMemoryRebound(to: B.self, capacity: 1) { | |
var z1 = $0 as UnsafeMutablePointer<B> | |
var bbbb : B = B() | |
bbbb = z1.pointee | |
print ("bbbb.j \(bbbb.j)") | |
} | |
ptr.withMemoryRebound(to: C.self, capacity: 1) { | |
var z2 = $0 as UnsafeMutablePointer<C> | |
var cccc : C = C() | |
cccc = z2.pointee | |
print ("cccc.j \(cccc.j)") | |
} | |
ptr.withMemoryRebound(to: D.self, capacity: 1) { | |
var z3 = $0 as UnsafeMutablePointer<D> | |
var dddd : D = D() | |
dddd = z3.pointee | |
print ("dddd.j \(dddd.j)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment