Hi-jack NSLog under Xamarin iOS

113 views Asked by At

I'm working on a debug feature, that shows an in-app log console inspired by https://github.com/duraidabdul/LocalConsole.

In the perfect world I want to hi-jack NSLog and show messages in the log console, but it's not straight forward. I even remember trying this many years ago in Obj-C.

This is what I got so far, it runs without exceptions, but LogCString is never called:

public static class NSLogHiJacker
{
    public static void HiJack()
    {
        try
        {
            var del = new LogCStringDelegate(LogCString);
            IntPtr func = Marshal.GetFunctionPointerForDelegate(del);
            var handle = GCHandle.Alloc(func);
            NSSetLogCStringFunction(func);
            handle.Free();
            Console.WriteLine("NSLog was hi-jacked!");
        }
        catch (Exception e)
        {
            // ignored
        }
    }

    [DllImport(Constants.ObjectiveCLibrary, EntryPoint = "_NSSetLogCStringFunction")]
    private extern static void NSSetLogCStringFunction(IntPtr funcPointer);

    [MonoNativeFunctionWrapper]
    public delegate void LogCStringDelegate (IntPtr message, UIntPtr length, bool withSyslogBanner);

    [MonoPInvokeCallback (typeof (LogCStringDelegate))]
    public static void LogCString(IntPtr message, UIntPtr length, bool withSyslogBanner)
    {
        // Now what?
    }
}

Anybody tried this before? I know it's one big hack, but I don't care, since it's a debug feature that will never hit App Store.

0

There are 0 answers