Skip to content

Instantly share code, notes, and snippets.

@luiseduardohd
Created November 25, 2017 11:52
Show Gist options
  • Save luiseduardohd/495465e2f49669edb07f1cd8a51b32ac to your computer and use it in GitHub Desktop.
Save luiseduardohd/495465e2f49669edb07f1cd8a51b32ac to your computer and use it in GitHub Desktop.
Xamarin swizzle
using System;
using System.Runtime.InteropServices;
using MonoTouch.ObjCRuntime;
using MonoTouch.Foundation;
namespace XamarinSwizzle
{
[Register("TestClass")]
public class TestCode : NSObject
{
public TestCode() : base()
{
}
static TestCode()
{
ExchangeMethods();
}
public void Run()
{
objc_msgSend(this.Handle, Selector.GetHandle("layoutSubviews"));
objc_msgSend(this.Handle, Selector.GetHandle("myLayoutSubviews"));
}
[DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "method_exchangeImplementations")]
private static extern void method_exchangeImplementations (IntPtr existingMethod, IntPtr newMethod);
[DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "class_getInstanceMethod")]
private static extern IntPtr class_getInstanceMethod (IntPtr classHandle, IntPtr selectorHandle);
[DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")]
private static extern void objc_msgSend (IntPtr receiver, IntPtr selector);
private static void ExchangeMethods()
{
var classHandle = Class.GetHandle("TestClass");
var s1 = Selector.GetHandle("layoutSubviews");
var s2 = Selector.GetHandle("myLayoutSubviews");
var m1 = class_getInstanceMethod(classHandle, s1);
var m2 = class_getInstanceMethod(classHandle, s2);
// this won't work since http://forums.xamarin.com/discussion/comment/51694/#Comment_51694
method_exchangeImplementations(m1, m2);
}
[Export("myLayoutSubviews")]
private void myLayoutSubviews()
{
Console.WriteLine("myLayoutSubviews");
}
[Export("layoutSubviews")]
private void layoutSubviews()
{
Console.WriteLine("layoutSubviews");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment