Created
March 29, 2012 10:43
-
-
Save fjolnir/2235769 to your computer and use it in GitHub Desktop.
Objc method observer
This file contains hidden or 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
objc = require("objc") | |
ffi = require("ffi") | |
setmetatable(_G, {__index=objc}) | |
objc.debug=false | |
ffi.cdef("IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types);") | |
local C = ffi.C | |
function observeMethod(class, sel, lambda) | |
local method = C.class_getInstanceMethod(class, SEL(sel)) | |
if method == nil then | |
error("Error! Method not found") | |
end | |
local impTypeStr = objc.impSignatureForMethod(method) | |
if impTypeStr == nil then | |
return nil | |
end | |
local originalImp = C.method_getImplementation(method) | |
local trampoline = ffi.cast(impTypeStr, function(self, sel, ...) | |
lambda(self, ...) | |
return originalImp(self, sel, ...) | |
end) | |
C.class_replaceMethod(class, SEL(sel), ffi.cast("IMP", trampoline), C.method_getTypeEncoding(method)) | |
end | |
observeMethod(Cube, "render:", function(self, state) | |
print("Render called") | |
end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment