Skip to content

Instantly share code, notes, and snippets.

@rolfbjarne
Created May 27, 2015 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolfbjarne/9a0b0c0b7e8306d3ac58 to your computer and use it in GitHub Desktop.
Save rolfbjarne/9a0b0c0b7e8306d3ac58 to your computer and use it in GitHub Desktop.
public static class DebugConstraint
{
delegate IntPtr DescriptionDelegate (IntPtr self, IntPtr sel);
static DescriptionDelegate newDescImpl = new DescriptionDelegate (Description);
public static void Swizzle ()
{
var constraintClass = Class.GetHandle (typeof(NSLayoutConstraint));
var method = class_getInstanceMethod (constraintClass, Selector.GetHandle ("description"));
var originalImpl = class_getMethodImplementation (constraintClass, Selector.GetHandle ("description"));
// add the original implementation to respond to 'customDescription'
class_addMethod (constraintClass, Selector.GetHandle ("customDescription"), originalImpl, "@@:");
// replace the original implementation with our own for the 'descriptor' method.
var newImpl = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate (newDescImpl);
method_setImplementation (method, newImpl);
}
[ObjCRuntime.MonoPInvokeCallback (typeof (DescriptionDelegate))]
public static IntPtr Description (IntPtr self, IntPtr sel)
{
var originalDescPtr = objc_msgSend (self, Selector.GetHandle ("customDescription"));
var originalDesc = Runtime.GetNSObject<NSString> (originalDescPtr);
Console.WriteLine ("Original desc: {0}", originalDesc);
return new NSString ("my version").Handle;
}
[System.Runtime.InteropServices.DllImport ("libobjc.dylib")]
static extern IntPtr objc_msgSend (IntPtr handle, IntPtr sel);
[System.Runtime.InteropServices.DllImport ("libobjc.dylib")]
static extern IntPtr class_getInstanceMethod (IntPtr c, IntPtr sel);
[System.Runtime.InteropServices.DllImport ("libobjc.dylib")]
static extern bool class_addMethod (IntPtr cls, IntPtr name, IntPtr imp, string types);
[System.Runtime.InteropServices.DllImport ("libobjc.dylib")]
extern static IntPtr class_getMethodImplementation (IntPtr cls, IntPtr sel);
[System.Runtime.InteropServices.DllImport ("libobjc.dylib")]
extern static IntPtr method_setImplementation (IntPtr method, IntPtr imp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment