// This file was generated by the Gtk# code generator.
// Any changes made will be lost if regenerated.

namespace GLibSharp {

	using System;
	using System.Runtime.InteropServices;

#region Autogenerated code
	[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
	internal delegate bool SourceFuncNative(IntPtr user_data);

	internal class SourceFuncInvoker {

		SourceFuncNative native_cb;
		IntPtr __data;
		GLib.DestroyNotify __notify;

		~SourceFuncInvoker ()
		{
			if (__notify == null)
				return;
			__notify (__data);
		}

		internal SourceFuncInvoker (SourceFuncNative native_cb) : this (native_cb, IntPtr.Zero, null) {}

		internal SourceFuncInvoker (SourceFuncNative native_cb, IntPtr data) : this (native_cb, data, null) {}

		internal SourceFuncInvoker (SourceFuncNative native_cb, IntPtr data, GLib.DestroyNotify notify)
		{
			this.native_cb = native_cb;
			__data = data;
			__notify = notify;
		}

		internal GLib.SourceFunc Handler {
			get {
				return new GLib.SourceFunc(InvokeNative);
			}
		}

		bool InvokeNative (IntPtr user_data)
		{
			bool __result = native_cb (__data);
			return __result;
		}
	}

	internal class SourceFuncWrapper {

		public bool NativeCallback (IntPtr user_data)
		{
			try {
				bool __ret = managed (user_data);
				if (release_on_call)
					gch.Free ();
				return __ret;
			} catch (Exception e) {
				GLib.ExceptionManager.RaiseUnhandledException (e, false);
				return false;
			}
		}

		bool release_on_call = false;
		GCHandle gch;

		public void PersistUntilCalled ()
		{
			release_on_call = true;
			gch = GCHandle.Alloc (this);
		}

		internal SourceFuncNative NativeDelegate;
		GLib.SourceFunc managed;

		public SourceFuncWrapper (GLib.SourceFunc managed)
		{
			this.managed = managed;
			if (managed != null)
				NativeDelegate = new SourceFuncNative (NativeCallback);
		}

		public static GLib.SourceFunc GetManagedDelegate (SourceFuncNative native)
		{
			if (native == null)
				return null;
			SourceFuncWrapper wrapper = (SourceFuncWrapper) native.Target;
			if (wrapper == null)
				return null;
			return wrapper.managed;
		}
	}
#endregion
}
