//
// BlockBasementStaticTypeAutoViewController.swift
// iOS底层
//
// Created by yanqunchao on 2019/5/19.
// Copyright © 2019 yanqunchao. All rights reserved.
//
import UIKit
class BlockBasementStaticTypeAutoViewController: UIViewController {
typealias FuncPt = ((MainBlockImpl0)->())
class BlockImpl: NSObject {
var isa:UnsafeRawPointer?
var Flags:Int?
var Reserved:Int?
var FuncPtr:FuncPt? //函数地址,
}
/*
* 访问auto局部变量的Desc类
**/
class MainBlockDesc0: NSObject {
var reserved:Int?
var BlockSize:Int?
init(reserve:Int,blockSize:Int) {
reserved = reserve
BlockSize = blockSize
}
override init() {
}
}
/*
* 访问static局部变量的block类
**/
class MainBlockImpl0: NSObject {
var imp: BlockImpl?
var Desc: MainBlockDesc0?
var height: UnsafeMutablePointer<Int>? //局部变量的地址
init(fp:@escaping FuncPt,Desc:MainBlockDesc0,flag:Int,height:UnsafeMutablePointer<Int>) {
imp = BlockImpl()
// imp!.isa = &_NSConcreateStackBlock
imp?.Flags = flag
imp?.FuncPtr = fp
self.Desc = Desc
self.height = height
}
override init() {
}
}
/*
*block调用的函数地址
**/
func mainBlockFunc0(block:MainBlockImpl0){
print("调用mainBlockFunc0函数获取的变量值为\(block.height!.pointee)))")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func blockWithStaticLocalVar(){ // 访问static类型的局部变量的block
var staticHeight:Int = 10 //假设是静态局部变量(swift无法创建局部静态变量,无法模拟其场景)
let mainBlockDesc0Data = MainBlockDesc0(reserve: 0, blockSize: MemoryLayout.size(ofValue: MainBlockImpl0.self))
let block = MainBlockImpl0(fp: mainBlockFunc0, Desc: mainBlockDesc0Data,flag: 0, height: &staticHeight)
staticHeight = 20
block.imp?.FuncPtr!(block)
}
}
网友评论