Read() private méthode

private Read ( [ buffer, int offset, int count ) : int
buffer [
offset int
count int
Résultat int
Exemple #1
0
        private void UnpackBigEndian(string path)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            int count = *(bint*)(_source.Address + 0x08);

            for (int i = 0; i < count; i++)
                stringOffsets.Add(*(bint*)(_source.Address + (i * 0x04) + 0x10));
            for (int i = 0; i < count; i++)
                dataOffsets.Add(*(bint*)(_source.Address + (stringOffsets.Count * 4) + (i * 4) + 0x10));
            for (int i = 0; i < count; i++)
                sizes.Add(*(bint*)(_source.Address + (stringOffsets.Count * 4) + (dataOffsets.Count * 4) + (i * 4) + 0x10));

            foreach (int off in stringOffsets)
                strings.Add(new String((sbyte*)_source.Address + off));

            for (int i = 0; i < count; i++)
            {
                byte[] _fileData = new byte[sizes[i]];

                using (UnmanagedMemoryStream stream = new UnmanagedMemoryStream((byte*)(_source.Address + dataOffsets[i]), sizes[i]))
                    stream.Read(_fileData, 0, (int)stream.Length);

                try
                {
                    File.WriteAllBytes(path+"/" + strings[i], _fileData);
                }

                catch (Exception x) { Console.WriteLine(x.Message); }
            }
        }
Exemple #2
0
		public void ToStream(byte* ptr, long count, Stream output)
		{
			using (var stream = new UnmanagedMemoryStream(ptr, count))
			{
				while (stream.Position < stream.Length)
				{
					var read = stream.Read(_buffer, 0, _buffer.Length);
					output.Write(_buffer, 0, read);
				}
			}
		}
Exemple #3
0
		public override object GetData (TransferDataType type)
		{
			if (type == TransferDataType.Uri)
				return (Uri)NSUrl.FromPasteboard (NSPasteboard.GeneralPasteboard);

			var data = NSPasteboard.GeneralPasteboard.GetDataForType (type.ToUTI ());
			if (data == null)
				return null;

			if (type == TransferDataType.Text)
				return data.ToString ();
			if (type == TransferDataType.Image)
				return new NSImage (data);

			unsafe {
				var bytes = new byte [data.Length];
				using (var stream = new UnmanagedMemoryStream ((byte*)data.Bytes, bytes.Length))
					stream.Read (bytes, 0, bytes.Length);
				return TransferDataSource.DeserializeValue (bytes);
			}
		}
        unsafe public IHttpActionResult Unmanaged()
        {
            //使用 UnmanagedMemoryStream 类读取和写入非托管内存。 使用 Marshal 类分配和解除分配非托管内存块。
            // Create some data to read and write.
            byte[] message = UnicodeEncoding.Unicode.GetBytes("Hello Angkor");

            // Allocate a block of unmanaged memory and return an IntPtr object.	
            IntPtr memIntPtr = Marshal.AllocHGlobal(message.Length);

            // Get a byte pointer from the IntPtr object.
            byte* memBytePtr = (byte*)memIntPtr.ToPointer();

            // Create an UnmanagedMemoryStream object using a pointer to unmanaged memory.
            UnmanagedMemoryStream writeStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Write);

            // Write the data.
            writeStream.Write(message, 0, message.Length);
            // Close the stream.
            writeStream.Close();
            // Create another UnmanagedMemoryStream object using a pointer to unmanaged memory.
            UnmanagedMemoryStream readStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Read);
            // Create a byte array to hold data from unmanaged memory.
            byte[] outMessage = new byte[message.Length];
            // Read from unmanaged memory to the byte array.
            readStream.Read(outMessage, 0, message.Length);
            // Close the stream.
            readStream.Close();
            // Display the data to the console.

            var msg = UnicodeEncoding.Unicode.GetString(outMessage);
            // Free the block of unmanaged memory.
            Marshal.FreeHGlobal(memIntPtr);
            return Json(msg);


        }
 public static void PlaySoundResourceEvenIfNotPCM(UnmanagedMemoryStream unmanagedMemoryStream)
 {
     try
     {
         long n = unmanagedMemoryStream.Length;
         byte[] waveData = new byte[n];
         unmanagedMemoryStream.Read(waveData, 0, (int)n);
         // Note: I did not use SND_ASYNC here, because of the reasons described in this article: http://blogs.msdn.com/b/larryosterman/archive/2009/02/19/playsound-xxx-snd-memory-snd-async-is-almost-always-a-bad-idea.aspx
         PlaySound(waveData, 0, (int)(SND.SND_MEMORY | SND.SND_NOWAIT));
     }
     catch (Exception x)
     {
         Console.WriteLine("PlaySoundResourceEvenIfNotPCM: Error trying to access or play the resource: " + x.Message);
     }
 }
		public void Write ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, capacity, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, length);
			Assert.AreEqual (capacity, ums.Capacity, "#A1");
			Assert.AreEqual (length, ums.Position, "#A2");
			Assert.AreEqual (length, ums.Length, "#A3");
			ums.Position = 0;
			ums.Read (readData, 0, length);
			Assert.AreEqual (capacity, ums.Capacity, "#B1");
			Assert.AreEqual (length, ums.Position, "#B2");
			Assert.AreEqual (length, ums.Length, "#B3");
			VerifyTestData ("#B4", readData, 0, length);
			ums.Write (testStreamData, 2, 2);
			Assert.AreEqual (capacity, ums.Capacity, "#C1");
			Assert.AreEqual (length + 2, ums.Position, "#C1");
			Assert.AreEqual (length + 2, ums.Length, "#C2");
			ums.Position = length;
			Assert.AreEqual (testStreamData [2], ums.ReadByte (), "#D1");
			Assert.AreEqual (testStreamData [3], ums.ReadByte (), "#D2");
			ums.Close();
		}
		public void Read_WriteOnly ()
		{
			UnmanagedMemoryStream ums = new
				UnmanagedMemoryStream(mem_byteptr, length, length, FileAccess.Write);
			try {
				ums.Read(readData, 0, 1);
				Assert.Fail ("#1");
			} catch (NotSupportedException ex) {
				// Stream does not support reading
				Assert.AreEqual (typeof (NotSupportedException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
			}
			ums.Close();
		}
		public void Read_Count_Overflow ()
		{
			using (UnmanagedMemoryStream ums = new UnmanagedMemoryStream (mem_byteptr, length, length, FileAccess.ReadWrite)) {
				ums.Write (testStreamData, 0, testStreamData.Length);
				ums.Position = 0;
				try {
					ums.Read (readData, 0, Int32.MaxValue);
					Assert.Fail ("#1");
				}
				catch (ArgumentException ex) {
					Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
					Assert.IsNull (ex.ParamName, "#5");
				}
			}
		}
Exemple #9
0
        public void ATAwriteDMA8Mem(UnmanagedMemoryStream pMem, int size)
        {
            if (((xferMode & 0xF0) == 0x40) &&
                (dev9.Dev9Ru16((int)DEV9Header.SPD_R_IF_CTRL) & DEV9Header.SPD_IF_DMA_ENABLE) != 0)
            {
                //size >>= 1;
                Log_Verb("DEV9 : DMA write, size " + size + ", transferred " + wrTransferred + ", total size " + nsector * 512);
                Log_Info("wATA");

                //write
                byte[] temp = new byte[size];
                pMem.Read(temp, 0, size);
                hddImage.Write(temp, 0, size);

                wrTransferred += size;
                if (wrTransferred >= nsector * 512)
                {
                    hddImage.Flush();

                    //Set Sector
                    long currSect = HDD_GetLBA();
                    currSect += nsector;
                    HDD_SetLBA(currSect);

                    nsector = 0;
                    status = DEV9Header.ATA_STAT_READY | DEV9Header.ATA_STAT_SEEK;
                    if (sendIRQ) dev9.DEV9irq(3, 1); //0x6C
                    wrTransferred = 0;
                    //dev9.Dev9Wu16((int)DEV9Header.SPD_R_IF_CTRL, (UInt16)(dev9.Dev9Ru16((int)DEV9Header.SPD_R_IF_CTRL) & ~DEV9Header.SPD_IF_DMA_ENABLE));
                }
            }
        }
Exemple #10
0
 public override int Read([In, Out] byte[] buffer, int offset, int count)
 {
     return(_unmanagedStream.Read(buffer, offset, count));
 }
		public void Read_Count_Overlow ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, length, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;
			try {
				ums.Read (readData, 1, readData.Length);
				Assert.Fail ("#1");
			} catch (ArgumentException ex) {
				// Offset and length were out of bounds for the array or count
				// is greater than the number of elements from index to the end
				// of the source collection
				Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNull (ex.ParamName, "#5");
			}
		}
		public void Read_Stream_Closed ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length);
			ums.Close();
			ums.Read(readData, 0, 0);
		}
		public void Read_Buffer_Null ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length);
			try {
				ums.Read((byte []) null, 0, 0);
				Assert.Fail ("#1");
			} catch (ArgumentNullException ex) {
				// Value cannot be null
				Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNotNull (ex.ParamName, "#5");
				Assert.AreEqual ("buffer", ex.ParamName, "#6");
			}
		}
		public void Read ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, capacity, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;

			Assert.AreEqual (length / 2, ums.Read (readData, 0, (length / 2)), "#1");
			VerifyTestData ("#2", readData, 0, (length / 2));
			Assert.AreEqual (length / 2, ums.Position, "#3");
			
			//Seek back to begining
			ums.Seek (0, SeekOrigin.Begin);
			
			//Read complete stream
			Assert.AreEqual (length, ums.Read (readData, 0, length), "#4");
			VerifyTestData ("#5", readData, 0, length);
			Assert.AreEqual (length, ums.Position, "#6");
			
			//Seek to mid of the stream and read till end
			ums.Seek ((length / 2), SeekOrigin.Begin);
			ums.Read (readData, 0, (length / 2));
			VerifyTestData ("#7", readData, (length / 2), (length / 2));
			Assert.AreEqual (length, ums.Position, "#8");
			ums.Close ();
		}
Exemple #15
0
		unsafe static public MemoryPatch Patch(IntPtr target, Action action)
		{
			int size = 8;
			var mr = GetPermissions(target);
			if (mr != null) {
				MemoryProtection(target, size, mprot.Read|mprot.Write);
				var ums = new UnmanagedMemoryStream((byte *)target, 0, size, FileAccess.ReadWrite);

				byte[] unpatched = new byte[size];
				ums.Read(unpatched, 0, size);

				ums.Seek(0, SeekOrigin.Begin);
				var writer = new X86Writer(ums, (IntPtr)size);
				writer.Mov32(X86Register32.EAX, Marshal.GetFunctionPointerForDelegate(action).ToInt32());
				writer.Jmp(X86Register32.EAX);

				ums.Seek(0, SeekOrigin.Begin);
				byte[] patched = new byte[size];
				ums.Read(patched, 0, size);

				return new MemoryPatch(target, action, patched, unpatched);
			} else {
				throw new Exception();
			}
		}
		public override object GetData (TransferDataType type)
		{
			
			if (type == TransferDataType.Uri) {
				NSPasteboard pasteBoard = NSPasteboard.GeneralPasteboard;
				NSArray nsArray = (NSArray)pasteBoard.GetPropertyListForType(NSPasteboard.NSFilenamesType);
				NSString[] pathArray = NSArray.FromArray<NSString>(nsArray);
				if(pathArray != null) {
					string[] uriArray = new string[pathArray.Length];
					for(int i = 0; i < pathArray.Length; i++) {
						Uri fileUrl = new Uri(pathArray[i].ToString());
						if(fileUrl != null && fileUrl.IsFile) {
							uriArray[i] = pathArray[i].ToString();
						}
					}
					return uriArray;
				}
			}

			if(type == TransferDataType.Image) {
				NSPasteboard pasteBoard = NSPasteboard.GeneralPasteboard;
				string[] imageTypes = NSImage.ImageUnfilteredPasteboardTypes();
				for (int i = 0; i< imageTypes.Length; i++) {
					NSData imgData = pasteBoard.GetDataForType(imageTypes[i]);
					if(imgData != null) {
						NSImage nsImg = new NSImage(imgData);
						return ApplicationContext.Toolkit.WrapImage (nsImg);
					}
				}
			}

			// Url as text!
			if (type == TransferDataType.Text) {
				NSUrl url = NSUrl.FromPasteboard(NSPasteboard.GeneralPasteboard);
				if(url != null && url.IsFileUrl) {
					return "file://" + new Uri(url.Path).AbsolutePath;
				}
			}

			var data = NSPasteboard.GeneralPasteboard.GetDataForType (type.ToUTI ());
			if (data == null)
				return null;

			if (type == TransferDataType.Text)
				return data.ToString ();
			if (type == TransferDataType.Image)
				return ApplicationContext.Toolkit.WrapImage (new NSImage (data));

			unsafe {
				var bytes = new byte [data.Length];
				using (var stream = new UnmanagedMemoryStream ((byte*)data.Bytes, bytes.Length))
					stream.Read (bytes, 0, bytes.Length);
				try {
					return TransferDataSource.DeserializeValue(bytes);
				} catch(System.Runtime.Serialization.SerializationException) {
					// if data cannot be read, do not crash - return null
					return null;
				}
			}
		}
        private static unsafe void ThreadFunc()
        {
            try
            {
                int size = 65536;
                bool createdMain = false;
                var hFile = WinAPI.OpenFileMapping(
                    WinAPI.FileMapAccess.FileMapAllAccess,
                    false,
                    "ulHelper_fm");
                if (hFile == IntPtr.Zero)
                {
                    hFile = WinAPI.CreateFileMapping(
                        new IntPtr(-1),
                        IntPtr.Zero,
                        WinAPI.FileMapProtection.PageReadWrite,
                        (uint)0, (uint)size,
                        "ulHelper_fm");
                    createdMain = true;
                }
                var lpBaseAddress = WinAPI.MapViewOfFile(
                    hFile,
                    WinAPI.FileMapAccess.FileMapAllAccess,
                    0, 0, 0);

                Mutex = new Mutex(false, "ulHelper_mutex");
                Stream = new UnmanagedMemoryStream((byte*)lpBaseAddress.ToPointer(), size, size, FileAccess.ReadWrite);

                eventWH = new EventWaitHandle(false, EventResetMode.AutoReset, "ulHelper_event");

                int accCount;
                byte[] buf = new byte[size];

                if (createdMain)
                {
                    Mutex.WaitOne();
                    try
                    {
                        buf[0] = buf[1] = buf[2] = buf[3] = 0;
                        Stream.Position = 0;
                        Stream.Write(buf, 0, 4);
                    }
                    finally
                    {
                        Mutex.ReleaseMutex();
                    }
                }

                eventWH.Set();
                while (true)
                {
                    eventWH.WaitOne();
                    if (MainForm.NeedTerminate)
                        break;
                    Mutex.WaitOne();
                    try
                    {
                        Stream.Position = 0;
                        accCount = Stream.ReadByte();
                        lock (Accounts.List)
                            if (Accounts.List.Count != accCount)
                            {
                                foreach (var acc in Accounts.List)
                                    acc.Active = false;
                                for (int i = 0; i < accCount; i++)
                                {
                                    string accountName = "";
                                    int index = 0;
                                    Stream.Position = 8 + i * 128;
                                    Stream.Read(buf, 0, 128);
                                    while (buf[index] != 0)
                                        accountName += (char)buf[index++];
                                    if (!Accounts.List.Any(acc => acc.Name == accountName))
                                    {
                                        var accData = new AccountData(accountName);
                                        Accounts.List.Add(accData);
                                    }
                                    Accounts.List.First(acc => acc.Name == accountName).Active = true;
                                }
                                PerformNewAccount();
                            }
                    }
                    finally
                    {
                        Mutex.ReleaseMutex();
                    }
                }

                WinAPI.UnmapViewOfFile(lpBaseAddress);
                WinAPI.CloseHandle(hFile);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception ex)
            {
                var f = new ExceptionForm(ex);
                f.ShowDialog();
            }
        }
		public void Read_EndOfStream ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, length * 2, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			Assert.AreEqual (0, ums.Read (readData, 0, 1), "#1");
			ums.Seek(length + 1, SeekOrigin.Begin);
			Assert.AreEqual (0, ums.Read (readData, 0, 1), "#2");
			ums.Seek(length - 3, SeekOrigin.Begin);
			Assert.AreEqual (3, ums.Read (readData, 0, 5), "#3");
			ums.Seek(capacity + 1, SeekOrigin.Begin);
			Assert.AreEqual (0, ums.Read (readData, 0, 1), "#4");
			ums.Close ();
		}
		public void Read_Offset_Negative ()
		{
			UnmanagedMemoryStream ums = new 
				UnmanagedMemoryStream(mem_byteptr, length, length, FileAccess.ReadWrite);
			ums.Write (testStreamData, 0, testStreamData.Length);
			ums.Position = 0;
			try {
				ums.Read (readData, -1, 0);
				Assert.Fail ("#1");
			} catch (ArgumentOutOfRangeException ex) {
				// Non-negative number required
				Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNotNull (ex.ParamName, "#5");
				Assert.AreEqual ("offset", ex.ParamName, "#6");
			}
		}
Exemple #20
0
        /// <summary>
        /// Read sequence of bytes
        /// </summary>
        /// <param name="Buffer"></param>
        /// <param name="BytesToRead"></param>
        /// <param name="AtOffset"></param>
        /// <returns>Num bytes read</returns>
        public unsafe int Read(byte[] Buffer, int BytesToRead, Int64 AtOffset)
        {
            IntPtr hMVF = IntPtr.Zero;
            try
            {
                Int64 FileMapStart = (AtOffset / _AllocationGranularity) * _AllocationGranularity;
                Int64 MapViewSize = (AtOffset % _AllocationGranularity) + _AllocationGranularity;
                Int64 iViewDelta = AtOffset - FileMapStart;

                hMVF = Win32API.MapViewOfFile(_hMMF, Win32API.FileMapAccess.FileMapRead, FileMapStart, (Int32)MapViewSize);
                if (hMVF == IntPtr.Zero)
                    throw new Win32Exception();
                byte* p = (byte*)hMVF.ToPointer() + iViewDelta;
                UnmanagedMemoryStream ums = new UnmanagedMemoryStream(p, MapViewSize, MapViewSize, FileAccess.Read);
                byte[] ba = new byte[BytesToRead];
                return ums.Read(Buffer, 0, BytesToRead);
            }
            finally
            {
                if (hMVF != IntPtr.Zero)
                    Win32API.UnmapViewOfFile(hMVF);
            }
        }