swift 在swift中获取内部函数指针

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 在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)")

以上是关于swift 在swift中获取内部函数指针的主要内容,如果未能解决你的问题,请参考以下文章

从 Swift 调用带有数组指针和 int 指针的 C 函数

如何在 Swift 中声明、创建和使用方法指针?

具有内部函数和属性的 Swift 公共协议

Swift3.0语言教程使用指针创建和初始化字符串

在 Swift 中获取鼠标坐标

如何在 Swift 中对私有或内部函数进行单元测试?