Example #1
0
        Py_InitModule4(string name, IntPtr methodsPtr, string doc, IntPtr selfPtr, int apiver)
        {
            name = this.FixImportName(name);
            
            PythonDictionary methodTable = new PythonDictionary();
            PythonModule module = new PythonModule();
            this.AddModule(name, module);
            this.CreateModulesContaining(name);

            PythonDictionary __dict__ = module.Get__dict__();
            __dict__["__doc__"] = doc;
            __dict__["__name__"] = name;
            string __file__ = this.importFiles.Peek();
            __dict__["__file__"] = __file__;
            List __path__ = new List();
            if (__file__ != null)
            {
                __path__.append(Path.GetDirectoryName(__file__));
            }
            __dict__["__path__"] = __path__;
            __dict__["_dispatcher"] = new Dispatcher(this, methodTable, selfPtr);

            StringBuilder moduleCode = new StringBuilder();
            moduleCode.Append(CodeSnippets.USEFUL_IMPORTS);
            CallableBuilder.GenerateFunctions(moduleCode, methodsPtr, methodTable);
            this.ExecInModule(moduleCode.ToString(), module);
            
            return this.Store(module);
        }
        public static object Get__file__(NamespaceTracker self) {
            if (self.PackageAssemblies.Count == 1) {
                return self.PackageAssemblies[0].FullName;
            }

            List res = new List();
            for (int i = 0; i < self.PackageAssemblies.Count; i++) {
                res.append(self.PackageAssemblies[i].FullName);
            }
            return res;                        
        }
Example #3
0
        public static List getaddrinfo(
            CodeContext/*!*/ context,
            string host,
            object port,
            [DefaultParameterValue((int)AddressFamily.Unspecified)] int family,
            [DefaultParameterValue(0)] int socktype,
            [DefaultParameterValue((int)ProtocolType.IP)] int proto,
            [DefaultParameterValue((int)SocketFlags.None)] int flags
        ) {
            int numericPort;
            
            if (port == null) {
                numericPort = 0;
            } else if (port is int) {
                numericPort = (int)port;
            } else if (port is Extensible<int>) {
                numericPort = ((Extensible<int>)port).Value;
            } else if (port is string) {
                if (!Int32.TryParse((string)port, out numericPort)) {
                    // TODO: also should consult GetServiceByName                    
                    throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed");
                }
            } else if (port is ExtensibleString) {
                if (!Int32.TryParse(((ExtensibleString)port).Value, out numericPort)) {
                    // TODO: also should consult GetServiceByName                    
                    throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed");
                }
            } else {
                throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed");
            }

            if (socktype != 0) {
                // we just use this to validate; socketType isn't actually used
                System.Net.Sockets.SocketType socketType = (System.Net.Sockets.SocketType)Enum.ToObject(typeof(System.Net.Sockets.SocketType), socktype);
                if (socketType == System.Net.Sockets.SocketType.Unknown || !Enum.IsDefined(typeof(System.Net.Sockets.SocketType), socketType)) {
                    throw PythonExceptions.CreateThrowable(gaierror(context), PythonTuple.MakeTuple((int)SocketError.SocketNotSupported, "getaddrinfo failed"));
                }
            }

            AddressFamily addressFamily = (AddressFamily)Enum.ToObject(typeof(AddressFamily), family);
            if (!Enum.IsDefined(typeof(AddressFamily), addressFamily)) {
                throw PythonExceptions.CreateThrowable(gaierror(context), PythonTuple.MakeTuple((int)SocketError.AddressFamilyNotSupported, "getaddrinfo failed"));
            }

            // Again, we just validate, but don't actually use protocolType
            Enum.ToObject(typeof(ProtocolType), proto);

            IPAddress[] ips = HostToAddresses(context, host, addressFamily);

            List results = new List();

            foreach (IPAddress ip in ips) {
                results.append(PythonTuple.MakeTuple(
                    (int)ip.AddressFamily,
                    socktype,
                    proto,
                    "",
                    EndPointToTuple(new IPEndPoint(ip, numericPort))
                ));
            }

            return results;
        }
Example #4
0
        /// <summary>
        /// Process a sequence of objects that are compatible with ObjectToSocket(). Return two
        /// things as out params: an in-order List of sockets that correspond to the original
        /// objects in the passed-in sequence, and a mapping of these socket objects to their
        /// original objects.
        /// 
        /// The socketToOriginal mapping is generated because the CPython select module supports
        /// passing to select either file descriptor numbers or an object with a fileno() method.
        /// We try to be faithful to what was originally requested when we return.
        /// </summary>
        private static void ProcessSocketSequence(CodeContext context, object sequence, out List socketList, out Dictionary<Socket, object> socketToOriginal) {
            socketToOriginal = new Dictionary<Socket, object>();
            socketList = new List();

            IEnumerator cursor = PythonOps.GetEnumerator(sequence);
            while (cursor.MoveNext()) {
                object original = cursor.Current;
                Socket socket = ObjectToSocket(context, original);
                socketList.append(socket);
                socketToOriginal[socket] = original;
            }
        }
Example #5
0
            public List readlines([DefaultParameterValue(-1)]int size) {
                EnsureOpen();

                List lines = new List();
                for (Bytes line = readline(-1); line.Count > 0; line = readline(-1)) {
                    lines.append(line); 
                    if (size > 0) {
                        size -= line.Count;
                        if (size <= 0) {
                            break;
                        }
                    }
                }

                return lines;
            }
Example #6
0
        public static List nsmallest(CodeContext/*!*/ context, int n, object iterable) {
            if (n <= 0) {
                return new List();
            }

            List ret = new List(Math.Min(n, 4000)); // don't allocate anything too huge
            IEnumerator en = PythonOps.GetEnumerator(iterable);

            // populate list with first n items
            for (int i = 0; i < n; i++) {
                if (!en.MoveNext()) {
                    // fewer than n items; finish up here
                    HeapSort(context, ret);
                    return ret;
                }
                ret.append(en.Current);
            }

            // go through the remainder of the iterator, maintaining a max-heap of the n smallest values
            DoHeapifyMax(context, ret);
            while (en.MoveNext()) {
                DoPushPopMax(context, ret, en.Current);
            }

            // return the smallest items, in ascending order
            HeapSort(context, ret);
            return ret;
        }
Example #7
0
        private void ActualiseList(IntPtr ptr)
        {
            if (this.listsBeingActualised.ContainsKey(ptr))
            {
                throw new Exception("Fatal error: PythonMapper.listsBeingActualised is somehow corrupt");
            }

            List newList = new List();
            this.listsBeingActualised[ptr] = newList;

            int length = CPyMarshal.ReadIntField(ptr, typeof(PyListObject), "ob_size");
            if (length != 0)
            {
                IntPtr itemPtrPtr = CPyMarshal.ReadPtrField(ptr, typeof(PyListObject), "ob_item");
                for (int i = 0; i < length; i++)
                {
                    IntPtr itemPtr = CPyMarshal.ReadPtr(itemPtrPtr);
                    if (itemPtr == IntPtr.Zero)
                    {
                        // We have *no* idea what to do here.
                        throw new ArgumentException("Attempted to Retrieve uninitialised PyListObject -- expect strange bugs");
                    }

                    if (this.listsBeingActualised.ContainsKey(itemPtr))
                    {
                        newList.append(this.listsBeingActualised[itemPtr]);
                    }
                    else
                    {
                        newList.append(this.Retrieve(itemPtr));
                    }

                    itemPtrPtr = CPyMarshal.Offset(itemPtrPtr, CPyMarshal.PtrSize);
                }
            }
            this.listsBeingActualised.Remove(ptr);
            this.incompleteObjects.Remove(ptr);
            this.map.Associate(ptr, newList);
        }
Example #8
0
            public List keys()
            {
                List list = new List();

                for(int i = 0; i < data.Count; ++i)
                {
                    list.append(((PythonTuple)description[i])[0]);
                }

                return list;
            }
Example #9
0
            public IEnumerator GetEnumerator()
            {
                List results = new List();
                try
                {
                    while(true)
                        results.append(this.next(this.context));
                }
                catch(StopIterationException) { }

                return results.GetEnumerator();
            }
Example #10
0
            public override List readlines([DefaultParameterValue(null)]object hint) {
                _checkClosed();
                int size = GetInt(hint, -1);

                List lines = new List();
                for (Bytes line = readline(-1); line.Count > 0; line = readline(-1)) {
                    lines.append(line); 
                    if (size > 0) {
                        size -= line.Count;
                        if (size <= 0) {
                            break;
                        }
                    }
                }

                return lines;
            }
Example #11
0
 public List getRGB()
 {
     List list = new List();
     list.append(this.red);
     list.append(this.green);
     list.append(this.blue);
     return list;
 }
Example #12
0
 public List getRGB(int x, int y)
 {
     /*
       Returns a triple (r,g,b) of the red, green, and blue
       intensities of the pixel at (x,y). Intensity values are
       in range(256).
     */
     byte r, g, b;
     unsafe {
     byte *pixels = (byte *)this.pixbuf.Pixels;
     r = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 0];
     g = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 1];
     b = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 2];
     }
     List list = new List();
     list.append((int)r);
     list.append((int)g);
     list.append((int)b);
     return list;
 }