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

namespace PopplerSharp {

	using System;
	using System.Runtime.InteropServices;

#region Autogenerated code
	[GLib.CDeclCallback]
	internal delegate bool AttachmentSaveFuncNative(IntPtr buf, UIntPtr count, IntPtr data, out IntPtr error);

	internal class AttachmentSaveFuncInvoker {

		AttachmentSaveFuncNative native_cb;
		IntPtr __data;
		GLib.DestroyNotify __notify;

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

		internal AttachmentSaveFuncInvoker (AttachmentSaveFuncNative native_cb) : this (native_cb, IntPtr.Zero, null) {}

		internal AttachmentSaveFuncInvoker (AttachmentSaveFuncNative native_cb, IntPtr data) : this (native_cb, data, null) {}

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

		internal Poppler.AttachmentSaveFunc Handler {
			get {
				return new Poppler.AttachmentSaveFunc(InvokeNative);
			}
		}

		bool InvokeNative (string buf, ulong count)
		{
			IntPtr native_buf = GLib.Marshaller.StringToPtrGStrdup (buf);
			IntPtr error = IntPtr.Zero;
			bool result = native_cb (native_buf, new UIntPtr (count), __data, out error);
			GLib.Marshaller.Free (native_buf);
			return result;
		}
	}

	internal class AttachmentSaveFuncWrapper {

		public bool NativeCallback (IntPtr buf, UIntPtr count, IntPtr data, out IntPtr error)
		{
			error = IntPtr.Zero;

			try {
				bool __ret = managed (GLib.Marshaller.Utf8PtrToString (buf), (ulong) count);
				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 AttachmentSaveFuncNative NativeDelegate;
		Poppler.AttachmentSaveFunc managed;

		public AttachmentSaveFuncWrapper (Poppler.AttachmentSaveFunc managed)
		{
			this.managed = managed;
			if (managed != null)
				NativeDelegate = new AttachmentSaveFuncNative (NativeCallback);
		}

		public static Poppler.AttachmentSaveFunc GetManagedDelegate (AttachmentSaveFuncNative native)
		{
			if (native == null)
				return null;
			AttachmentSaveFuncWrapper wrapper = (AttachmentSaveFuncWrapper) native.Target;
			if (wrapper == null)
				return null;
			return wrapper.managed;
		}
	}
#endregion
}
