Esempio n. 1
0
 public List <byte[]> ReadList(ReadCallback cb)
 {
     if (NextInstructionIsAccessor())
     {
         cb();
     }
     try {
         CheckType(Instruction.LIST);
         // discard list type (enum head + enum byte)
         pop(2);
         int           num   = ReadIntLiteral(cb);
         List <byte[]> items = new List <byte[]>();
         for (int i = 0; i < num; i++)
         {
             CheckType(Instruction.LIST_ITEM);
             int    size  = ReadIntLiteral(cb);
             byte[] array = new byte[size];
             for (int j = 0; j < size; j++)
             {
                 array[j] = pop();
             }
             items.Add(array);
         }
         return(items);
     } catch (UnexpectedByteException e) {
         throw e;
     }
 }
Esempio n. 2
0
 public List <string> ReadCardList(ReadCallback cb)
 {
     if (NextInstructionIsAccessor())
     {
         cb();
     }
     try {
         CheckType(Instruction.LIST);
         ListType listType = (ListType)ReadEnumLiteral();
         if (listType != ListType.CARD)
         {
             throw new UnexpectedByteException("Expected card list, got list of type " + listType);
         }
         int           num   = ReadIntLiteral(cb);
         List <string> cards = new List <string>();
         for (int i = 0; i < num; i++)
         {
             CheckType(Instruction.LIST_ITEM);
             // discard size
             ReadIntLiteral(cb);
             cards.Add(ReadCardLiteral(cb));
         }
         return(cards);
     } catch (UnexpectedByteException e) {
         throw e;
     }
 }
Esempio n. 3
0
    public Condition ReadConditionLiteral(ReadCallback cb)
    {
        if (NextInstructionIsAccessor())
        {
            cb();
        }
        try {
            CheckType(Instruction.CONDITION);
            byte conditionType = ReadEnumLiteral();
            switch ((ConditionType)conditionType)
            {
            case ConditionType.BOOL: {
                bool a = ReadBoolLiteral(cb);
                ConditionOperator op = (ConditionOperator)ReadEnumLiteral();
                bool b = ReadBoolLiteral(cb);
                return(new Condition(a, b, op));
            }

            case ConditionType.NUM: {
                int a = ReadIntLiteral(cb);
                ConditionOperator op = (ConditionOperator)ReadEnumLiteral();
                int b = ReadIntLiteral(cb);
                return(new Condition(a, b, op));
            }

            default:
                throw new UnexpectedByteException("Didn't understand the condition type! " + conditionType);
            }
        } catch (UnexpectedByteException e) {
            throw e;
        }
    }
 /// <summary>Repeatedly calls <paramref name="read"/> until <paramref name="count"/> bytes have been read into
 /// <paramref name="buffer"/>.</summary>
 /// <exception cref="ArgumentNullException"><paramref name="read"/> equals <c>null</c>.</exception>
 /// <exception cref="EndOfStreamException">The end of the stream has been reached before
 /// <paramref name="buffer"/> could be filled to <paramref name="count"/> bytes.</exception>
 /// <exception cref="Exception"><paramref name="read"/> has thrown an exception.</exception>
 public static void Fill(ReadCallback read, byte[] buffer, int offset, int count)
 {
     if (count != TryFill(read, buffer, offset, count))
     {
         throw new EndOfStreamException("Unexpected end of stream.");
     }
 }
        public void FastRead(ReadCallback callback, int timeout)
        {
            var readDelegate = new ReadDelegate(FastRead);
            var asyncState   = new HidAsyncState(readDelegate, callback);

            readDelegate.BeginInvoke(timeout, EndRead, asyncState);
        }
Esempio n. 6
0
        public void Read(ReadCallback callback)
        {
            ReadDelegate  readDelegate = Read;
            HidAsyncState @object      = new HidAsyncState(readDelegate, callback);

            readDelegate.BeginInvoke(EndRead, @object);
        }
Esempio n. 7
0
        public static InteropSnapshot FromSnapshot(SnapshotBase snapshotBase)
        {
            // TODO: can this memory alternatively be addressed with Memory<T>?
            unsafe int CopyChars(byte *buffer, int offset, int count)
            {
                var chars = stackalloc char[count];

                for (int i = 0; i < count && (i + offset) < snapshotBase.Length; i++)
                {
                    chars[i] = snapshotBase[i + offset];
                }

                // TODO: this might have issues with encoding conversions of multi-char characters
                // at array boundaries.
                return(Encoding.UTF8.GetBytes(chars, count, buffer, count));
            }

            ReadCallback callback = CopyChars;

            // Ensure that the callback can't be GC-ed.
            // TODO: free?
            GCHandle.Alloc(callback);

            return(new InteropSnapshot(callback, snapshotBase.Length));
        }
    }
        public FlacReader(Stream input, WavWriter output)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }

            stream = input;
            writer = output;

            context = _flacStreamDecoderNew();

            if (context == IntPtr.Zero)
            {
                throw new ApplicationException("FLAC: Could not initialize stream decoder!");
            }

            write    = Write;
            metadata = Metadata;
            error    = Error;
            read     = Read;
            seek     = Seek;
            tell     = Tell;
            length   = Length;
            eof      = Eof;

            if (_flacStreamDecoderInitStream(context, read, seek, tell, length, eof, write, metadata,
                                             error, IntPtr.Zero) != 0)
            {
                throw new ApplicationException("FLAC: Could not open stream for reading!");
            }
        }
Esempio n. 9
0
        override public void Read(ReadCallback callback, int timeout)
        {
            if (!IsConnected)
            {
                return;
            }


            if (IsReadInProgress)
            {
                //UnityEngine.Debug.Log("Clone paket");
                __lastHIDReport.Status = HIDReport.ReadStatus.Buffered;

                callback.BeginInvoke(__lastHIDReport, EndReadCallback, callback);
                // callback.Invoke(__lastHIDReport);

                return;
            }

            IsReadInProgress = true;

            //TODO make this fields or use pool
            var readDelegate = new ReadDelegate(Read);
            var asyncState   = new HidAsyncState(readDelegate, callback);

            readDelegate.BeginInvoke(timeout, EndRead, asyncState);
        }
Esempio n. 10
0
 /// <summary>Repeatedly calls <paramref name="read"/> until <paramref name="count"/> bytes have been read into
 /// <paramref name="buffer"/>.</summary>
 /// <exception cref="ArgumentNullException"><paramref name="read"/> equals <c>null</c>.</exception>
 /// <exception cref="EndOfStreamException">The end of the stream has been reached before
 /// <paramref name="buffer"/> could be filled to <paramref name="count"/> bytes.</exception>
 /// <exception cref="Exception"><paramref name="read"/> has thrown an exception.</exception>
 public static void Fill(ReadCallback read, byte[] buffer, int offset, int count)
 {
     if (count != TryFill(read, buffer, offset, count))
     {
         throw new EndOfStreamException("Unexpected end of stream.");
     }
 }
Esempio n. 11
0
        public void Read(ReadCallback callback)
        {
            var readDelegate = new ReadDelegate(Read);
            var asyncState   = new HidAsyncState(readDelegate, callback);

            readDelegate.BeginInvoke(EndRead, asyncState);
        }
Esempio n. 12
0
        public virtual void Close()
        {
            if (handle == IntPtr.Zero)
            {
                return;
            }

            DisableReading();
            DisableWriting();

            read_watcher.Dispose();
            write_watcher.Dispose();
            timeout_watcher.Dispose();

            read_watcher    = null;
            write_watcher   = null;
            timeout_watcher = null;
            handle          = IntPtr.Zero;

            foreach (IWriteOperation op in write_ops)
            {
                op.Dispose();
            }
            write_ops.Clear();

            if (Closed != null)
            {
                Closed(this, EventArgs.Empty);
            }
            Closed        = null;
            read_callback = null;

            GC.SuppressFinalize(this);
        }
Esempio n. 13
0
 public Disassembler(ReadCallback readCallback)
 {
     readFunction    = readCallback;
     operands        = new Operand[4];
     operations      = new Dictionary <uint, Operation>();
     OverrideSegment = SegmentRegister.Default;
 }
Esempio n. 14
0
        public override void Read <TState>(ReadCallback <TState> callback, TState state = default(TState))
        {
            if (length == 0) // 无数据内容直接返回
            {
                callback(PacketData.Empty, state);
                return;
            }
            if (sourceOffset == sourceSize) // 已读取完加载后续包
            {
                packet.Dispose();
                trans.Input(OnDataInput <TState>, new object[] { callback, state });
                return;
            }
            // 将可用缓冲区移至起始位置
            if (sourceOffset > 0)
            {
                sourceSize -= sourceOffset;
                Array.Copy(source, sourceOffset, source, 0, sourceSize);
            }
            // 获取数据块大小
            var dataSize = length > sourceSize ? sourceSize : length;

            length      -= dataSize;
            sourceOffset = dataSize;
            callback(new PacketData(this, source, dataSize), state);
        }
Esempio n. 15
0
 public Disassembler(ReadCallback readCallback)
 {
     readFunction = readCallback;
     operands = new Operand[4];
     operations = new Dictionary<uint, Operation>();
     OverrideSegment = SegmentRegister.Default;
 }
Esempio n. 16
0
        public void Read(ReadCallback callback, int timeout)
        {
            var d          = new _ReadDelegate(Read);
            var asyncState = new AsyncState(d, callback);

            d.BeginInvoke(timeout, _EndRead, asyncState);
        }
Esempio n. 17
0
        public override void Read <TState>(ReadCallback <TState> callback, TState state = default(TState))
        {
            var data = new PacketData(this, this.data?.Buffer, this.data?.Size ?? 0);

            this.data.Dispose();
            callback(data, state);
        }
Esempio n. 18
0
 public void ReadStart(AllocCallback allocCallback, ReadCallback readCallback, object allocState, object readState)
 {
     this.mAllocCallback      = allocCallback;
     this.mReadCallback       = readCallback;
     this.mReadCallbackState  = readState;
     this.mAllocCallbackState = allocState;
     UVIntrop.read_start(this, mOnAlloc, mOnRead);
 }
Esempio n. 19
0
        public void ReadBytes(ReadCallback callback)
        {
            EnableReading();

            read_callback = callback;

            UpdateExpires();
        }
Esempio n. 20
0
        private void SetupIOEntry(ushort port, ReadCallback read, WriteCallback write)
        {
            var entry = new IOEntry {
                Read = read, Write = write
            };

            ioPorts.Add(port, entry);
        }
Esempio n. 21
0
        void IPacket.Read <TState>(ReadCallback <TState> callback, TState state)
        {
            var size = this.size;

            this.size     = NoData;                 // 已读取后,清空缓冲区
            this.disposed = true;                   // 自动释放
            callback(new PacketData(this, buffer, size), state);
        }
Esempio n. 22
0
        /// <summary>
        /// Begin asynchronous reading of data
        /// </summary>
        /// <param name="callback">The function to be called when data is done being read</param>
        public void ReadAsync(ReadCallback callback)
        {
            ReadDelegate del = new ReadDelegate(Read);

            del.BeginInvoke(AsyncReadEnd, new object[2] {
                del, callback
            });
        }
Esempio n. 23
0
 public PrintStack(List <byte> bytes)
 {
     stack = new List <byte>();
     for (int i = 0; i < bytes.Count; i++)
     {
         push(bytes[i]);
     }
     readAccessorFirst = ReadAccessorFirst;
 }
Esempio n. 24
0
        override public void Read(ReadCallback callback)
        {
            if (!IsConnected)
            {
                return;
            }

            Read(callback, 0);
        }
Esempio n. 25
0
        protected void EndReadCallback(IAsyncResult ar)
        {
            // Because you passed your original delegate in the asyncState parameter
            // of the Begin call, you can get it back here to complete the call.
            ReadCallback dlgt = (ReadCallback)ar.AsyncState;

            // Complete the call.
            dlgt.EndInvoke(ar);
        }
Esempio n. 26
0
        protected static void EndRead(IAsyncResult ar)
        {
            HidAsyncState hidAsyncState = (HidAsyncState)ar.AsyncState;
            ReadDelegate  readDelegate  = (ReadDelegate)hidAsyncState.CallerDelegate;
            ReadCallback  readCallback  = (ReadCallback)hidAsyncState.CallbackDelegate;
            HidDeviceData data          = readDelegate.EndInvoke(ar);

            readCallback?.Invoke(data);
        }
Esempio n. 27
0
        public void GetServoPositions(int[] servos, ReadCallback callback = null)
        {
            DataWriter dataWriter = new DataWriter();

            dataWriter.WriteByte((byte)servos.Length);
            dataWriter.WriteBytes(servos.Select(i => (byte)i).ToArray());

            SendHidReport(RobotCommand.ServoPositionRead, dataWriter.DetachBuffer());
            device.Read(callback, Timeout);
        }
Esempio n. 28
0
        /// <summary>
        /// Called when bytes finish being read
        /// </summary>
        /// <param name="res">Contains the delegates involved in the read</param>
        private void AsyncReadEnd(IAsyncResult res)
        {
            // Pull the read function and callback out of the IAsyncResult
            object[]     objects  = res.AsyncState as object[];
            ReadDelegate del      = objects[0] as ReadDelegate;
            ReadCallback callback = objects[1] as ReadCallback;

            // Send the data up to the controller class
            callback.Invoke(del.EndInvoke(res));
        }
Esempio n. 29
0
 void IPacket.Read <TState>(ReadCallback <TState> callback, TState state)
 {
     if (body == null)
     {
         callback(new PacketData(this, null, 0), state);
     }
     else
     {
         body.Read(callback, state);
     }
 }
Esempio n. 30
0
        /// <summary>Initializes a new instance of the <see cref="ReadBuffer"/> class.</summary>
        /// <param name="read">The method that is called when the buffer needs to be filled.</param>
        /// <param name="bufferSize">The size of the buffer in bytes.</param>
        /// <exception cref="ArgumentNullException"><paramref name="read"/> equals <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="bufferSize"/> is 0 or negative.</exception>
        public ReadBuffer(ReadCallback read, int bufferSize)
            : base(bufferSize)
        {
            if (read == null)
            {
                throw new ArgumentNullException(nameof(read));
            }

            this.read = read;
            this.readAsync = (b, o, c, t) => ThrowInvalidAsyncOperationException();
        }
Esempio n. 31
0
 public void Read <TState>(ReadCallback <TState> callback, TState state)
 {
     if (bodySize <= 0)
     {
         callback(new PacketData(null, null, 0), state);
     }
     else
     {
         data.GetPacketData(bodySize, OnRead <TState>, new object[] { callback, state });
     }
 }
        /// <summary>Initializes a new instance of the <see cref="ReadBuffer"/> class.</summary>
        /// <param name="read">The method that is called when the buffer needs to be filled.</param>
        /// <param name="bufferSize">The size of the buffer in bytes.</param>
        /// <exception cref="ArgumentNullException"><paramref name="read"/> equals <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="bufferSize"/> is 0 or negative.</exception>
        public ReadBuffer(ReadCallback read, int bufferSize)
            : base(bufferSize)
        {
            if (read == null)
            {
                throw new ArgumentNullException(nameof(read));
            }

            this.read      = read;
            this.readAsync = (b, o, c, t) => ThrowInvalidAsyncOperationException();
        }
Esempio n. 33
0
    public GameMaster()
    {
        Bytes     = new Interpreter(this);
        Cards     = new CardManager();
        Functions = new GameFunctions();
        Players   = new PlayerManager(4);
        Variables = new GameVariables();

        // change this outside of testing
        UI = new DummyUI();

        queryCheck = QueryBeforeRead;
    }
Esempio n. 34
0
        /// <summary>Repeatedly calls <paramref name="read"/> until <paramref name="count"/> bytes have been read into
        /// <paramref name="buffer"/> or the end of the stream has been reached.</summary>
        /// <returns>The number of bytes read.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="read"/> equals <c>null</c>.</exception>
        /// <exception cref="Exception"><paramref name="read"/> has thrown an exception.</exception>
        public static int TryFill(ReadCallback read, byte[] buffer, int offset, int count)
        {
            if (read == null)
            {
                throw new ArgumentNullException(nameof(read));
            }

            int index = offset;
            int readCount;

            while ((readCount = read(buffer, index, count)) > 0)
            {
                index += readCount;
                count -= readCount;
            }

            return index - offset;
        }
Esempio n. 35
0
		public Genesis(CoreComm comm, GameInfo game, byte[] rom)
		{
			ServiceProvider = new BasicServiceProvider(this);
			CoreComm = comm;
			MainCPU = new MC68000();
			SoundCPU = new Z80A();
			YM2612 = new YM2612() { MaxVolume = 23405 };
			PSG = new SN76489() { MaxVolume = 4681 };
			VDP = new GenVDP();
			VDP.DmaReadFrom68000 = ReadWord;
			(ServiceProvider as BasicServiceProvider).Register<IVideoProvider>(VDP);
			SoundMixer = new SoundMixer(YM2612, PSG);

			MainCPU.ReadByte = ReadByte;
			MainCPU.ReadWord = ReadWord;
			MainCPU.ReadLong = ReadLong;
			MainCPU.WriteByte = WriteByte;
			MainCPU.WriteWord = WriteWord;
			MainCPU.WriteLong = WriteLong;
			MainCPU.IrqCallback = InterruptCallback;

			// ---------------------- musashi -----------------------
#if MUSASHI
			_vdp = vdpcallback;
			read8 = Read8;
			read16 = Read16;
			read32 = Read32;
			write8 = Write8;
			write16 = Write16;
			write32 = Write32;

			Musashi.RegisterVdpCallback(Marshal.GetFunctionPointerForDelegate(_vdp));
			Musashi.RegisterRead8(Marshal.GetFunctionPointerForDelegate(read8));
			Musashi.RegisterRead16(Marshal.GetFunctionPointerForDelegate(read16));
			Musashi.RegisterRead32(Marshal.GetFunctionPointerForDelegate(read32));
			Musashi.RegisterWrite8(Marshal.GetFunctionPointerForDelegate(write8));
			Musashi.RegisterWrite16(Marshal.GetFunctionPointerForDelegate(write16));
			Musashi.RegisterWrite32(Marshal.GetFunctionPointerForDelegate(write32));
#endif
			// ---------------------- musashi -----------------------

			SoundCPU.ReadMemory = ReadMemoryZ80;
			SoundCPU.WriteMemory = WriteMemoryZ80;
			SoundCPU.WriteHardware = (a, v) => { Console.WriteLine("Z80: Attempt I/O Write {0:X2}:{1:X2}", a, v); };
			SoundCPU.ReadHardware = x => 0xFF;
			SoundCPU.IRQCallback = () => SoundCPU.Interrupt = false;
			Z80Reset = true;
			RomData = new byte[0x400000];
			for (int i = 0; i < rom.Length; i++)
				RomData[i] = rom[i];

			SetupMemoryDomains();
#if MUSASHI
			Musashi.Init();
			Musashi.Reset();
			VDP.GetPC = () => Musashi.PC;
#else
			MainCPU.Reset();
			VDP.GetPC = () => MainCPU.PC;
#endif
			InitializeCartHardware(game);
		}
 /// <summary>
 /// Initialises a new instance of the ExtendedReadState class, using the specified parameters.
 /// </summary>
 /// <param name="client">The TcpClient from which the data has been read.</param>
 /// <param name="buffer">The buffer containing the read data.</param>
 /// <param name="callback">The ReadCallback which should be called by the calling code when the 
 /// relevant operation is done.</param>
 public ExtendedReadState(TcpClient client, byte[] buffer, ReadCallback callback)
     : base(client, buffer)
 {
     this.Callback = callback;
 }
Esempio n. 37
0
		public void DisableReading ()
		{
			read_callback = null;
			read_watcher.Stop ();
		}
Esempio n. 38
0
 public void FastRead(ReadCallback callback, int timeout)
 {
     var readDelegate = new ReadDelegate(FastRead);
     var asyncState = new HidAsyncState(readDelegate, callback);
     readDelegate.BeginInvoke(timeout, EndRead, asyncState);
 }
Esempio n. 39
0
 public void OnRead( ReadCallback callback )
 {
     readCallback = callback;
 }
Esempio n. 40
0
        private void FinishRead(int end)
        {
            ReadCallback callback = read_callback;
            byte [] data = read_buffer.GetBuffer ();
            byte [] read = new byte [end];

            Array.Copy (data, 0, read, 0, end);

            int length = (int) read_buffer.Position;

            read_bytes = -1;
            read_delimiter = null;
            last_delimiter_check = -1;
            read_callback = null;

            read_buffer.Position = 0;
            read_buffer.Write (data, end, length - end);

            callback (this, read);
        }
 public SocketClient(string host, int port, ReadCallback clientReadCallback)
 {
     this.host = host;
     this.port = port;
     this.clientReadCallback = clientReadCallback;
 }
Esempio n. 42
0
        public void ReadUntil(string delimiter, ReadCallback callback)
        {
            CheckCanRead ();

            read_delimiter = Encoding.ASCII.GetBytes (delimiter);
            read_callback = callback;

            int di = FindDelimiter ();
            if (di != -1) {
                FinishRead (di);
                return;
            }

            AddIOState (IOLoop.EPOLL_READ_EVENTS);
        }
Esempio n. 43
0
 /// <summary>
 /// Waits and receives data from the remote server, and passes it on to a callback.
 /// </summary>
 /// <param name="callback">The ReadCallback to pass data to when the operation completes.</param>
 public void Receive(ReadCallback callback)
 {
     NetworkStream stream;
     try
     {
         stream = _client.GetStream();
     }
     catch (InvalidOperationException)
     {
         _window.AddMessage("fatal: failed to receive new messages", "Server", Colors.Crimson);
         _window.Dispatcher.BeginInvoke(new Action(delegate()
         {
             _window.SendButton.IsEnabled = false;
             _window.MessageInput.IsEnabled = false;
         }));
         return;
     }
     while (!stream.DataAvailable)
     {
         Thread.Sleep(50);
     }
     byte[] readBuffer = new byte[_client.Available];
     stream.BeginRead(readBuffer, 0, readBuffer.Length, ReceiveCallbackInternal,
         new ExtendedReadState(_client, readBuffer, callback));
 }
Esempio n. 44
0
 public virtual void Read(ReadCallback callback)
 {
     throw new NotImplementedException();
 }
Esempio n. 45
0
        public void ReadBytes(ReadCallback callback)
        {
            EnableReading();

            read_callback = callback;

            UpdateExpires();
        }
Esempio n. 46
0
        private void FinishRead(int end)
        {
            ReadCallback callback = read_callback;
            byte [] data = read_buffer.GetBuffer ();
            byte [] read = new byte [end];

            Array.Copy (data, 0, read, 0, end);

            read_bytes = -1;
            read_delimiter = null;
            read_callback = null;
            read_buffer.Close ();
            read_buffer = new MemoryStream ();
            read_buffer.Write (data, end, data.Length - end);

            callback (this, read);

            DisableReading ();
        }
Esempio n. 47
0
        public void ReadBytes(int num_bytes, ReadCallback callback)
        {
            CheckCanRead ();

            read_bytes = num_bytes;
            read_callback = callback;

            if (read_buffer != null && read_buffer.Position >= num_bytes) {
                FinishRead (num_bytes);
                return;
            }

            EnableReading ();
        }
Esempio n. 48
0
        public void ReadBytes(int num_bytes, ReadCallback callback)
        {
            CheckCanRead ();

            read_bytes = num_bytes;
            read_callback = callback;

            if (read_buffer != null && read_buffer.Length >= num_bytes) {
                FinishRead (num_bytes);
                return;
            }

            AddIOState (IOLoop.EPOLL_READ_EVENTS);
        }
Esempio n. 49
0
        public void ReadUntil(string delimiter, ReadCallback callback)
        {
            CheckCanRead ();

            read_delimiter = Encoding.ASCII.GetBytes (delimiter);
            read_callback = callback;

            int di = FindDelimiter ();
            if (di != -1) {
                FinishRead (di);
                return;
            }

            EnableReading ();
        }
Esempio n. 50
0
        /// <summary>
        /// 尝试读取目标对象指定成员的值,处理基础类型、特殊类型、基础类型数组、特殊类型数组,通过委托方法处理成员
        /// </summary>
        /// <remarks>
        /// 简单类型在value中返回,复杂类型直接填充target;
        /// </remarks>
        /// <param name="target">目标对象</param>
        /// <param name="member">成员</param>
        /// <param name="type">成员类型,以哪一种类型读取</param>
        /// <param name="encodeInt">是否编码整数</param>
        /// <param name="allowNull">是否允许空</param>
        /// <param name="isProperty">是否处理属性</param>
        /// <param name="value">成员值</param>
        /// <param name="callback">处理成员的方法</param>
        /// <returns>是否读取成功</returns>
        public Boolean TryReadObject(Object target, MemberInfoX member, Type type, Boolean encodeInt, Boolean allowNull, Boolean isProperty, out Object value, ReadCallback callback)
        {
            if (type == null)
            {
                type = member.Type;
                if (target != null && member.IsType) type = target.GetType();
            }
            if (callback == null) callback = ReadMember;

            // 基本类型
            if (TryReadValue(type, encodeInt, out value)) return true;

            // 特殊类型
            if (TryReadX(type, out value)) return true;

            #region 枚举
            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                return TryReadEnumerable(target, member, encodeInt, allowNull, isProperty, out value, callback);
            }
            #endregion

            #region 复杂对象
            // 引用类型允许空时,先读取一个字节判断对象是否为空
            if (!type.IsValueType && allowNull && !ReadBoolean()) return true;

            // 成员对象
            //if (member.Member.MemberType == MemberTypes.TypeInfo)
            //    value = target;
            //else
            //    value = member.GetValue(target);
            value = member.IsType ? target : member.GetValue(target);

            // 如果为空,实例化并赋值。只有引用类型才会进来
            if (value == null)
            {
                value = TypeX.CreateInstance(type);
                //// 如果是成员,还需要赋值
                //if (member.Member.MemberType != MemberTypes.TypeInfo && target != null) member.SetValue(target, value);
            }

            // 以下只负责填充value的各成员
            Object obj = null;
            if (isProperty)
            {
                PropertyInfo[] pis = BinaryWriterX.FindProperties(type);
                if (pis == null || pis.Length < 1) return true;

                foreach (PropertyInfo item in pis)
                {
                    //ReadMember(target, reader, item, encodeInt, allowNull);
                    MemberInfoX member2 = item;
                    if (!callback(this, value, member2, member2.Type, encodeInt, allowNull, isProperty, out obj, callback)) return false;
                    member2.SetValue(value, obj);
                }
            }
            else
            {
                FieldInfo[] fis = BinaryWriterX.FindFields(type);
                if (fis == null || fis.Length < 1) return true;

                foreach (FieldInfo item in fis)
                {
                    //#if DEBUG
                    //                    long p = 0;
                    //                    long p2 = 0;
                    //                    if (BaseStream.CanSeek && BaseStream.CanRead)
                    //                    {
                    //                        p = BaseStream.Position;
                    //                        Console.Write("{0,-16}:", item.Name);
                    //                    }
                    //#endif
                    //ReadMember(target, this, item, encodeInt, allowNull);
                    MemberInfoX member2 = item;
                    if (!callback(this, value, member2, member2.Type, encodeInt, allowNull, isProperty, out obj, callback)) return false;
                    // 尽管有可能会二次赋值(如果callback调用这里的话),但是没办法保证用户的callback一定会给成员赋值,所以这里多赋值一次
                    member2.SetValue(value, obj);
                    //#if DEBUG
                    //                    if (BaseStream.CanSeek && BaseStream.CanRead)
                    //                    {
                    //                        p2 = BaseStream.Position;
                    //                        if (p2 > p)
                    //                        {
                    //                            BaseStream.Seek(p, SeekOrigin.Begin);
                    //                            Byte[] data = new Byte[p2 - p];
                    //                            BaseStream.Read(data, 0, data.Length);
                    //                            Console.WriteLine("[{0}] {1}", data.Length, BitConverter.ToString(data));
                    //                        }
                    //                        else
                    //                            Console.WriteLine();
                    //                    }
                    //#endif
                }
            }
            #endregion

            return true;
        }
Esempio n. 51
0
        private void SetupIOEntry(ushort port, ReadCallback read, WriteCallback write)
        {
            var entry = new IOEntry {Read = read, Write = write};

            ioPorts.Add(port, entry);
        }
Esempio n. 52
0
 private static Boolean ReadMember(BinaryReaderX reader, Object target, MemberInfoX member, Type type, Boolean encodeInt, Boolean allowNull, Boolean isProperty, out Object value, ReadCallback callback)
 {
     // 使用自己作为处理成员的方法
     return reader.TryReadObject(target, member, type, encodeInt, allowNull, isProperty, out value, callback);
 }
Esempio n. 53
0
 public void FastRead(ReadCallback callback)
 {
     FastRead(callback, 0);
 }
Esempio n. 54
0
        /// <summary>
        /// 尝试读取枚举
        /// </summary>
        /// <remarks>重点和难点在于如果得知枚举元素类型,这里假设所有元素类型一致,否则实在无法处理</remarks>
        /// <param name="target">目标对象</param>
        /// <param name="member">成员</param>
        /// <param name="encodeInt">是否编码整数</param>
        /// <param name="allowNull">是否允许空</param>
        /// <param name="isProperty">是否处理属性</param>
        /// <param name="value">成员值</param>
        /// <param name="callback">处理成员的方法</param>
        /// <returns>是否读取成功</returns>
        public Boolean TryReadEnumerable(Object target, MemberInfoX member, Boolean encodeInt, Boolean allowNull, Boolean isProperty, out Object value, ReadCallback callback)
        {
            value = null;
            if (member == null || !typeof(IEnumerable).IsAssignableFrom(member.Type)) return false;

            //// 尝试计算元素类型,通过成员的第一个元素。这个办法实在丑陋,不仅要给成员赋值,还要加一个元素
            //Type elmType = null;
            //if (target != null && !member.IsType)
            //{
            //    IEnumerable en = member.GetValue(target) as IEnumerable;
            //    if (en != null)
            //    {
            //        foreach (Object item in en)
            //        {
            //            if (item != null)
            //            {
            //                elmType = item.GetType();
            //                break;
            //            }
            //        }
            //    }
            //}

            if (!TryReadEnumerable(member.Type, Type.EmptyTypes, encodeInt, allowNull, isProperty, out value, callback)) return false;

            if (!member.IsType) member.SetValue(target, value);

            return true;
        }
Esempio n. 55
0
    public void Read(ReadCallback callback, int timeout)
    {
      var d = new _ReadDelegate(Read);
      var asyncState = new AsyncState(d, callback);

      d.BeginInvoke(timeout, _EndRead, asyncState);
    }
Esempio n. 56
0
        /// <summary>
        /// 尝试读取枚举
        /// </summary>
        /// <remarks>重点和难点在于如果得知枚举元素类型,这里假设所有元素类型一致,否则实在无法处理</remarks>
        /// <param name="type">类型</param>
        /// <param name="elementTypes">元素类型数组</param>
        /// <param name="encodeInt">是否编码整数</param>
        /// <param name="allowNull">是否允许空</param>
        /// <param name="isProperty">是否处理属性</param>
        /// <param name="value">成员值</param>
        /// <param name="callback">处理成员的方法</param>
        /// <returns>是否读取成功</returns>
        public Boolean TryReadEnumerable(Type type, Type[] elementTypes, Boolean encodeInt, Boolean allowNull, Boolean isProperty, out Object value, ReadCallback callback)
        {
            value = null;
            if (!typeof(IEnumerable).IsAssignableFrom(type)) return false;

            Type elementType = null;
            Type valueType = null;
            if (elementTypes != null)
            {
                if (elementTypes.Length >= 1) elementType = elementTypes[0];
                if (elementTypes.Length >= 2) valueType = elementTypes[1];
            }

            //// 列表
            //if (typeof(IList).IsAssignableFrom(type))
            //{
            //    if (TryReadList(type, elementType, encodeInt, allowNull, isProperty, out value, callback)) return true;
            //}

            //// 字典
            //if (typeof(IDictionary).IsAssignableFrom(type))
            //{
            //    if (TryReadDictionary(type, elementType, valueType, encodeInt, allowNull, isProperty, out value, callback)) return true;
            //}

            // 先读元素个数
            Int32 count = ReadEncodedInt32();
            if (count < 0) throw new InvalidOperationException("无效元素个数" + count + "!");

            // 没有元素
            if (count == 0) return true;

            #region 计算元素类型
            if (elementTypes == null || elementTypes.Length <= 0)
            {
                if (type.HasElementType)
                    elementTypes = new Type[] { type.GetElementType() };
                else if (type.IsGenericType)
                {
                    Type[] ts = type.GetGenericArguments();
                    if (ts != null && ts.Length > 0)
                    {
                        if (ts.Length == 1)
                            elementTypes = new Type[] { ts[0] };
                        else if (ts.Length == 2)
                            elementTypes = new Type[] { ts[0], ts[1] };
                    }
                }
                if (elementTypes != null)
                {
                    if (elementTypes.Length >= 1) elementType = elementTypes[0];
                    if (elementTypes.Length >= 2) valueType = elementTypes[1];
                }
            }

            value = null;
            // 如果不是基本类型和特殊类型,必须有委托方法
            if (elementType == null || !Support(elementType) && callback == null) return false;
            #endregion

            #region 特殊处理字节数组和字符数组
            if (TryReadValue(type, encodeInt, out value)) return true;
            #endregion

            #region 多数组取值
            //Array arr = Array.CreateInstance(elementType, count);
            //Array arr = TypeX.CreateInstance(elementType.MakeArrayType(), count) as Array;
            Array[] arrs = new Array[elementTypes.Length];
            for (int i = 0; i < count; i++)
            {
                //if (allowNull && ReadEncodedInt32() == 0) continue;

                for (int j = 0; j < elementTypes.Length; j++)
                {
                    if (arrs[j] == null) arrs[j] = TypeX.CreateInstance(elementTypes[j].MakeArrayType(), count) as Array;

                    Object obj = null;
                    if (!TryReadValue(elementTypes[j], encodeInt, out obj) &&
                        !TryReadX(elementTypes[j], out obj))
                    {
                        //obj = CreateInstance(elementType);
                        //Read(obj, reader, encodeInt, allowNull, member.Member.MemberType == MemberTypes.Property);

                        //obj = TypeX.CreateInstance(elementType);
                        if (!callback(this, null, elementTypes[j], null, encodeInt, allowNull, isProperty, out obj, callback)) return false;
                    }
                    arrs[j].SetValue(obj, i);
                }
            }
            #endregion

            //value = arr;
            //if (!type.IsArray) value = Activator.CreateInstance(type, arr);
            //if (!type.IsArray) value = TypeX.CreateInstance(type, arr);

            #region 结果处理
            // 如果是数组,直接赋值
            if (type.IsArray)
            {
                value = arrs[0];
                return true;
            }
            else
            {
                if (arrs.Length == 1)
                {
                    // 检查类型是否有指定类型的构造函数,如果有,直接创建类型,并把数组作为构造函数传入
                    ConstructorInfoX ci = ConstructorInfoX.Create(type, new Type[] { typeof(IEnumerable) });
                    if (ci == null) ci = ConstructorInfoX.Create(type, new Type[] { typeof(IEnumerable<>).MakeGenericType(elementType) });
                    if (ci != null)
                    {
                        //value = TypeX.CreateInstance(type, arrs[0]);
                        value = ci.CreateInstance(arrs[0]);
                        return true;
                    }

                    // 添加方法
                    MethodInfoX method = MethodInfoX.Create(type, "Add", new Type[] { elementType });
                    if (method != null)
                    {
                        value = TypeX.CreateInstance(type);
                        for (int i = 0; i < count; i++)
                        {
                            method.Invoke(value, arrs[0].GetValue(i));
                        }
                        return true;
                    }
                }
                else if (arrs.Length == 2)
                {
                    // 检查类型是否有指定类型的构造函数,如果有,直接创建类型,并把数组作为构造函数传入
                    ConstructorInfoX ci = ConstructorInfoX.Create(type, new Type[] { typeof(IDictionary<,>).MakeGenericType(elementType, valueType) });
                    if (ci != null)
                    {
                        Type dicType = typeof(Dictionary<,>).MakeGenericType(elementType, valueType);
                        IDictionary dic = TypeX.CreateInstance(dicType) as IDictionary;
                        for (int i = 0; i < count; i++)
                        {
                            dic.Add(arrs[0].GetValue(i), arrs[1].GetValue(i));
                        }
                        //value = TypeX.CreateInstance(type, dic);
                        value = ci.CreateInstance(dic);
                        return true;
                    }

                    // 添加方法
                    MethodInfoX method = MethodInfoX.Create(type, "Add", new Type[] { elementType, valueType });
                    if (method != null)
                    {
                        value = TypeX.CreateInstance(type);
                        for (int i = 0; i < count; i++)
                        {
                            method.Invoke(value, arrs[0].GetValue(i), arrs[1].GetValue(i));
                        }
                        return true;
                    }
                }
            }
            #endregion

            return false;
        }
Esempio n. 57
0
 public void Read(ReadCallback callback)
 {
     var readDelegate = new ReadDelegate(Read);
     var asyncState = new HidAsyncState(readDelegate, callback);
     readDelegate.BeginInvoke(EndRead, asyncState);
 }
Esempio n. 58
0
        public virtual void Close()
        {
            if (handle == IntPtr.Zero)
                return;

            DisableReading ();
            DisableWriting ();

            read_watcher.Dispose ();
            write_watcher.Dispose ();
            timeout_watcher.Dispose ();

            read_watcher = null;
            write_watcher = null;
            timeout_watcher = null;
            handle = IntPtr.Zero;

            foreach (IWriteOperation op in write_ops) {
                op.Dispose ();
            }
            write_ops.Clear ();

            if (Closed != null)
                Closed (this, EventArgs.Empty);
            Closed = null;
            read_callback = null;
        }
Esempio n. 59
0
 public void Read(ReadCallback callback)
 {
     Read(callback, 0);
 }
 internal static extern void SnapshotManager_Read(
     HandleRef self,
      /* from(SnapshotMetadata_t) */ IntPtr snapshot_metadata,
      /* from(SnapshotManager_ReadCallback_t) */ ReadCallback callback,
      /* from(void *) */ IntPtr callback_arg);