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

namespace GstSharp {

	using System;
	using System.Runtime.InteropServices;

#region Autogenerated code
	[UnmanagedFunctionPointer (CallingConvention.Cdecl)]
	internal delegate void IteratorForeachFunctionNative(IntPtr item, IntPtr user_data);

	internal class IteratorForeachFunctionInvoker {

		IteratorForeachFunctionNative native_cb;
		IntPtr __data;
		GLib.DestroyNotify __notify;

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

		internal IteratorForeachFunctionInvoker (IteratorForeachFunctionNative native_cb) : this (native_cb, IntPtr.Zero, null) {}

		internal IteratorForeachFunctionInvoker (IteratorForeachFunctionNative native_cb, IntPtr data) : this (native_cb, data, null) {}

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

		internal Gst.IteratorForeachFunction Handler {
			get {
				return new Gst.IteratorForeachFunction(InvokeNative);
			}
		}

		void InvokeNative (GLib.Value item)
		{
			IntPtr native_item = GLib.Marshaller.StructureToPtrAlloc (item);
			native_cb (native_item, __data);
			Marshal.FreeHGlobal (native_item);
		}
	}

	internal class IteratorForeachFunctionWrapper {

		public void NativeCallback (IntPtr item, IntPtr user_data)
		{
			try {
				managed ((GLib.Value) Marshal.PtrToStructure (item, typeof (GLib.Value)));
				if (release_on_call)
					gch.Free ();
			} catch (Exception e) {
				GLib.ExceptionManager.RaiseUnhandledException (e, false);
			}
		}

		bool release_on_call = false;
		GCHandle gch;

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

		internal IteratorForeachFunctionNative NativeDelegate;
		Gst.IteratorForeachFunction managed;

		public IteratorForeachFunctionWrapper (Gst.IteratorForeachFunction managed)
		{
			this.managed = managed;
			if (managed != null)
				NativeDelegate = new IteratorForeachFunctionNative (NativeCallback);
		}

		public static Gst.IteratorForeachFunction GetManagedDelegate (IteratorForeachFunctionNative native)
		{
			if (native == null)
				return null;
			IteratorForeachFunctionWrapper wrapper = (IteratorForeachFunctionWrapper) native.Target;
			if (wrapper == null)
				return null;
			return wrapper.managed;
		}
	}
#endregion
}
