Skip to content

Instantly share code, notes, and snippets.

@Skifary Skifary/main.m
Last active Mar 12, 2019

Embed
What would you like to do?
替换block原有实现
#import <Foundation/Foundation.h>
typedef struct __block_impl {
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
}__block_impl;
typedef void(^GlobalBlock)(void);
void hookFunc() {
NSLog(@"hello world");
}
void HookBlockToPrintHelloWorld(id blk) {
__block_impl *ptr = (__bridge __block_impl *)blk;
ptr->FuncPtr = &hookFunc;
}
int main(int argc, const char * argv[]) {
GlobalBlock blk = ^void() {
};
HookBlockToPrintHelloWorld(blk);
blk();
return 0;
}
@Skifary

This comment has been minimized.

Copy link
Owner Author

Skifary commented Jun 16, 2018

问题源自:实现下面的函数,将block的实现修改成NSLog(@"hello world"),也就是说,在调完整个函数后调用block()时,并不调用原始实现,而是打“Hello world”
void HookBlockToPrintHelloWorld(id block) {

}

@Skifary

This comment has been minimized.

Copy link
Owner Author

Skifary commented Jun 16, 2018

原理:参照block内部结构,修改其函数指针即可改变任意block的函数部分

@lexrus

This comment has been minimized.

Copy link

lexrus commented Jun 28, 2018

如果想先调用原始实现,再打印 Hello world 呢?

@Skifary

This comment has been minimized.

Copy link
Owner Author

Skifary commented Jun 28, 2018

@lexrus 用一个函数指针保存原有的实现,在hookFunc里面调用一下就可以了

@songxing10000

This comment has been minimized.

Copy link

songxing10000 commented Jun 30, 2018

膜拜大神!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.