Skip to content

Instantly share code, notes, and snippets.

@fjolnir
Created March 29, 2012 10:43
Show Gist options
  • Save fjolnir/2235769 to your computer and use it in GitHub Desktop.
Save fjolnir/2235769 to your computer and use it in GitHub Desktop.
Objc method observer
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