[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/saroad2/pythonnet/master/src/runtime/iterator.cs [Back]  [Original]

using System;
using System.Collections;

namespace Python.Runtime
{
    /// 
    /// Implements a generic Python iterator for IEnumerable objects and
    /// managed array objects. This supports 'for i in object:' in Python.
    /// 
    internal class Iterator : ExtensionType
    {
        private IEnumerator iter;
        private Type elemType;

        public Iterator(IEnumerator e, Type elemType)
        {
            iter = e;
            this.elemType = elemType;
        }


        /// 
        /// Implements support for the Python iteration protocol.
        /// 
        public static IntPtr tp_iternext(IntPtr ob)
        {
            var self = GetManagedObject(ob) as Iterator;
            try
            {
                if (!self.iter.MoveNext())
                {
                    Exceptions.SetError(Exceptions.StopIteration, Runtime.PyNone);
                    return IntPtr.Zero;
                }
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                Exceptions.SetError(e);
                return IntPtr.Zero;
            }
            object item = self.iter.Current;
            return Converter.ToPython(item, self.elemType);
        }

        public static IntPtr tp_iter(IntPtr ob)
        {
            Runtime.XIncref(ob);
            return ob;
        }
    }
}

Web Proxy Viewer  |  New URL  |  Original Page