Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get the internal function pointer in swift
/// See
/// https://github.com/rodionovd/SWRoute/wiki/Function-hooking-in-Swift
/// https://github.com/rodionovd/SWRoute/blob/master/SWRoute/rd_get_func_impl.c
/// to find why this works
func peekFunc<A,R>(f:A->R)->(fp:Int, ctx:Int) {
let (hi, lo):(Int, Int) = reinterpretCast(f)
let offset = sizeof(Int) == 8 ? 16 : 12
let ptr = UnsafePointer<Int>(lo+offset)
return (ptr.memory, ptr.successor().memory)
}
@infix func === <A,R>(lhs:A->R,rhs:A->R)->Bool {
let (tl, tr) = (peekFunc(lhs), peekFunc(rhs))
return tl.0 == tr.0 && tl.1 == tr.1
}
// simple functions
func genericId<T>(t:T)->T { return t }
func incr(i:Int)->Int { return i + 1 }
var f:Int->Int = genericId
var g = f; println("(f === g) == \(f === g)")
f = genericId; println("(f === g) == \(f === g)")
f = g; println("(f === g) == \(f === g)")
// closures
func mkcounter()->()->Int {
var count = 0;
return { count++ }
}
var c0 = mkcounter()
var c1 = mkcounter()
var c2 = c0
println("peekFunc(c0) == \(peekFunc(c0))")
println("peekFunc(c1) == \(peekFunc(c1))")
println("peekFunc(c2) == \(peekFunc(c2))")
println("(c0() == c1()) == \(c0() == c1())") // true : both are called once
println("(c0() == c2()) == \(c0() == c2())") // false: because c0() means c2()
println("(c0 === c1) == \(c0 === c1)")
println("(c0 === c2) == \(c0 === c2)")
@devxoul

This comment has been minimized.

Copy link

@devxoul devxoul commented Jul 22, 2017

In Swift 3+

func peekFunc<A, R>(_ f: (A) -> R) -> (fp: Int, ctx: Int) {
  typealias IntInt = (Int, Int)
  let (_, lo) = unsafeBitCast(f, to: IntInt.self)
  let offset = MemoryLayout<Int>.size == 8 ? 16 : 12
  let ptr = UnsafePointer<Int>(bitPattern: lo + offset)!
  return (ptr.pointee, ptr.successor().pointee)
}

func === <A, R>(lhs: (A) -> R, rhs: (A) -> R) -> Bool {
  let (tl, tr) = (peekFunc(lhs), peekFunc(rhs))
  return tl.0 == tr.0 && tl.1 == tr.1
}
@kallipigous

This comment has been minimized.

Copy link

@kallipigous kallipigous commented Jun 14, 2018

I'm getting an error on Xcode 10 for this function.

Converting non-escaping value to 'T' may allow it to escape

on this line

let (_, lo) = unsafeBitCast(f, to: IntInt.self)

Any thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment