Just find a very tricky way to “extract” the function address, and the function seems be invoked successfully. But it’s still failed to run properly, because the access to NSException parameter will cause error.
public static class FuncHelper {
struct FuncBlock {
public void *isa;
public int flags;
public int reserved;
public NativeUInt address;
public void* dp;
}
public static Void* getPointer(object func) {
return (Void*)((FuncBlock*)(*((NativeUInt*)(&func))))->address;
}
}
public delegate void ExceptionHandlerFunc(NSException ex);
// Try to declare a global function instead of a member function
public static void onUncaughtException(NSException exception) {
var reason = exception.reason; // EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
Foundation.NSLog(reason);
}
[UIApplicationMain, IBObject]
class AppDelegate : IUIApplicationDelegate {
public BOOL application(UIApplication application) didFinishLaunchingWithOptions(NSDictionary launchOptions) {
var window = new UIWindow(UIScreen.mainScreen().bounds);
window.rootViewController = new UIViewController withNibName(null) bundle(null);
window.makeKeyAndVisible();
// setup & throw
ExceptionHandlerFunc func = onUncaughtException;
NSSetUncaughtExceptionHandler(FuncHelper.getPointer(func));
throw NSException.exceptionWithName("") reason("TEST ONLY") userInfo(null);
return true;
}
}
Isn’t NSSetUncaughtExceptionHandler defined as: void NSSetUncaughtExceptionHandler(NSUncaughtExceptionHandler *);
? If so you can use that type (NSUncaughtExceptionHandler). Elements on Cocoa has two different kinds of delegates: “Blocks” and “Function Pointers”. Currently delegates map to blocks (blocks have a “this” pointer, function pointers don’t). We don’t yet have a syntax for function pointers in C#. However to satisfy above method signature you need to define a static method outside a class (just move it before or after your class). Then you can use it as the parameter for this call.