Esempio n. 1
0
 private void button4_Click(object sender, EventArgs e)
 {
     try
     {
         using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("procfile"))
         {
             using (MemoryMappedViewStream stream = mmf.CreateViewStream(1, 0))
             {
                 BinaryWriter writer = new BinaryWriter(stream);
                 writer.Write(4);
                 sem.Release();
             }
             this.Text = "button4";
         }
     }
     catch (WaitHandleCannotBeOpenedException)
     {
         this.Text = "Memory-mapped file does not exist. Run Process A first.";
     }
 }
        public void AllowFinaliation()
        {
            // Explicitly do not dispose, to allow finalization to happen, just to try to verify
            // that nothing fails when it does.
            MemoryMappedFile       mmf = MemoryMappedFile.CreateNew(null, 4096);
            MemoryMappedViewStream s   = mmf.CreateViewStream();

            var mmfWeak = new WeakReference <MemoryMappedFile>(mmf);
            var sWeak   = new WeakReference <MemoryMappedViewStream>(s);

            mmf = null;
            s   = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            Assert.False(mmfWeak.TryGetTarget(out mmf));
            Assert.False(sWeak.TryGetTarget(out s));
        }
        /// <summary>
        /// Read the current physics data from shared memory
        /// </summary>
        /// <returns>A Physics object representing the current status, or null if not available</returns>
        public Physics ReadPhysics()
        {
            if (memoryStatus == AC_MEMORY_STATUS.DISCONNECTED || physicsMMF == null)
            {
                throw new AssettoCorsaNotStartedException();
            }

            using (var stream = physicsMMF.CreateViewStream())
            {
                using (var reader = new BinaryReader(stream))
                {
                    var size   = Marshal.SizeOf(typeof(Physics));
                    var bytes  = reader.ReadBytes(size);
                    var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                    var data   = (Physics)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Physics));
                    handle.Free();
                    return(data);
                }
            }
        }
Esempio n. 4
0
        internal PluginFileSource(string filePath, PluginFile plugin)
        {
            this.filePath = filePath;
            this.plugin   = plugin;
            fileInfo      = new FileInfo(filePath);
            plugin.source = this;
            var baseStream = new FileStream(
                filePath, FileMode.Open,
                FileAccess.Read, FileShare.ReadWrite
                );

            file = MemoryMappedFile.CreateFromFile(
                baseStream, null, 0, MemoryMappedFileAccess.Read,
                HandleInheritability.None, false
                );
            fileStream = file.CreateViewStream(
                0, 0, MemoryMappedFileAccess.Read
                );
            fileReader = new BinaryReader(stream);
        }
Esempio n. 5
0
        public void Attach()
        {
            if (Data != null && Data.Rows.Count > 0)
            {
                return;
            }

            using (FileStream fs = new(Path.Combine(TempFolder, Tag + ".cache"), FileMode.Open))
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs,
                                                                              Tag,
                                                                              fs.Length,
                                                                              MemoryMappedFileAccess.ReadWrite,
                                                                              HandleInheritability.None,
                                                                              false))
                    using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, fs.Length, MemoryMappedFileAccess.Read))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        Data = (DataTable)formatter.Deserialize(stream);
                    }
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            MemoryMappedFile       mmf     = MemoryMappedFile.CreateNew("AAB", 1024);
            MemoryMappedViewStream mStream = mmf.CreateViewStream();
            BinaryWriter           bw      = new BinaryWriter(mStream);
            Mutex mx = new Mutex(true, "sync");

            while (true)
            {
                mx.WaitOne();
                Thread.Sleep(2000);
                var random    = new Random();
                var nextValue = random.Next().ToString();
                Console.WriteLine(nextValue);
                bw.Write(nextValue);
                mx.ReleaseMutex();
            }
            bw.Close();
            mStream.Close();
        }
Esempio n. 7
0
 public bool runTest()
 {
     try
     {
         using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("MMVS_Dispose0", Int16.MaxValue))
         {
             // Dispose twice
             MemoryMappedViewStream view1 = mmf.CreateViewStream();
             view1.Dispose();
             view1.Dispose();
             view1.Dispose();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex);
         return(false);
     }
     return(true);
 }
Esempio n. 8
0
        void WriteSenderNamesToMemoryMap(List <string> senders)
        {
            bool createdNew;
            var  mutex = new Mutex(true, CSenderNamesHandle + "_mutex", out createdNew);

            if (mutex == null)
            {
                return;
            }

            try
            {
                mutex.WaitOne(CSpoutWaitTimeout);
                using (var vs = FSenderNamesMap.CreateViewStream())
                {
                    for (int i = 0; i < CMaxSenders; i++)
                    {
                        byte[] bytes;
                        if (i < senders.Count)
                        {
                            bytes = GetNameBytes(senders[i]);
                        }
                        else //fill with 0s
                        {
                            bytes = new byte[CSenderNameLength];
                        }

                        vs.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            catch (AbandonedMutexException e)
            {
                //Log.Add(e);
            }
            finally
            {
                mutex.ReleaseMutex();
                mutex.Dispose();
            }
        }
Esempio n. 9
0
        public override void StartClientSide(ICoreClientAPI api)
        {
            _api = api;
            api.Event.RegisterGameTickListener(OnGameTick, 20);

            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                var fileName = $"/dev/shm/MumbleLink.{getuid()}";

                void OnCreated(object sender, FileSystemEventArgs e)
                {
                    Mod.Logger.Notification("Link established");
                    _mappedFile = MemoryMappedFile.CreateFromFile(fileName);
                    _stream     = _mappedFile.CreateViewStream(0, MumbleLinkData.Size);
                }

                void OnDeleted(object sender, FileSystemEventArgs e)
                {
                    Mod.Logger.Notification("Link lost");
                    _stream.Dispose();
                    _mappedFile.Dispose();
                    _stream     = null;
                    _mappedFile = null;
                }

                if (File.Exists(fileName))
                {
                    OnCreated(null, null);
                }

                _watcher                     = new FileSystemWatcher(Path.GetDirectoryName(fileName), Path.GetFileName(fileName));
                _watcher.Created            += OnCreated;
                _watcher.Deleted            += OnDeleted;
                _watcher.EnableRaisingEvents = true;
            }
            else
            {
                _mappedFile = MemoryMappedFile.CreateOrOpen("MumbleLink", MumbleLinkData.Size);
                _stream     = _mappedFile.CreateViewStream(0, MumbleLinkData.Size);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// starts new process, in wich plane starts flight
        /// </summary>
        /// <param name="planeId">id of plane to start flight</param>
        /// <returns>task object wich starts process for flight</returns>
        public Task StartFlight(int planeId)
        {
            if (!CheckIfActive(planeId))
            {
                var plane       = GetPlaneById(planeId);
                var planeString = plane.JsonOut();

                return(Task.Run(() =>
                {
                    var fileName = Guid.NewGuid().ToString();
                    var mutexName = Guid.NewGuid().ToString();
                    var bufferSize = Encoding.Default.GetByteCount(planeString);

                    using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(fileName, bufferSize))
                    {
                        bool mutexCreated;
                        Mutex mutex = new Mutex(true, mutexName, out mutexCreated);
                        using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                        {
                            BinaryWriter writer = new BinaryWriter(stream);
                            writer.Write(planeString);
                        }
                        mutex.ReleaseMutex();

                        InterprocessDTO dto = new InterprocessDTO()
                        {
                            MemoryMappedFileName = fileName,
                            MutexName = mutexName
                        };

                        _dtos.Add(planeId, dto);

                        var process = Process.Start(Display.ToString(), fileName + " " + mutexName);
                        process?.WaitForExit();

                        _dtos.Remove(planeId);
                    }
                }));
            }
            return(null);
        }
        public MethodAddressToTokenMap(string filePath)
        {
            myMapFile = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read);

            var headerView = myMapFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);

            myAccessor = headerView;

            headerView.Read(0, out myHeader);

            if (myHeader.Magic != Magic)
            {
                myMapFile.Dispose();
                throw new FileLoadException($"File magic mismatched for {filePath}; Expected {Magic:X}, got {myHeader.Magic:X}");
            }

            if (myHeader.Version != Version)
            {
                myMapFile.Dispose();
                throw new FileLoadException($"File version mismatched for {filePath}; Expected {Version}, got {myHeader.Version}");
            }

            var offset = Marshal.SizeOf <FileHeader>();

            using var reader = new BinaryReader(myMapFile.CreateViewStream(offset, 0, MemoryMappedFileAccess.Read), Encoding.UTF8, false);
            for (var i = 0; i < myHeader.NumAssemblies; i++)
            {
                var assemblyName = reader.ReadString();
                myAssemblyList.Add(Assembly.Load(assemblyName));
            }

            unsafe
            {
                byte *pointersPointer = null;

                myAccessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointersPointer);

                myPointers = (long *)(pointersPointer + myHeader.DataOffset);
                myValues   = (int *)(pointersPointer + myHeader.DataOffset + myHeader.NumMethods * 8);
            }
        }
        void IPCsetup()
        {
            TextChangedEvent    = EventWaitHandle.OpenExisting("ewhTabTipKeyboard");
            TextFieldClearEvent = EventWaitHandle.OpenExisting("ewhTabTipClear");
            mmf = MemoryMappedFile.CreateOrOpen("hookTabTip", SIZE, MemoryMappedFileAccess.ReadWrite);
            TextFieldDataStream = mmf.CreateViewStream(0, SIZE);

            var thread = new Thread(() =>
            {
                while (true)
                {
                    TextFieldClearEvent.WaitOne();
                    Application.Current.Dispatcher.Invoke(new Action(() => {
                        textField.Text = "";
                    }));
                }
            });

            thread.IsBackground = true;
            thread.Start();
        }
Esempio n. 13
0
 private static void InitializeIndexIfNeeded()
 {
     if (_memoryFile != null)
     {
         return;
     }
     _memoryFile       = MemoryMappedFile.CreateFromFile(FILE_PATH, FileMode.Open);
     _memoryFileStream = _memoryFile.CreateViewStream();
     _index            = new Dictionary <string, Entry>();
     using (var binaryReader = new BinaryReader(_memoryFileStream, Encoding.Default, true))
     {
         var count = binaryReader.ReadInt32();
         for (var i = 0; i < count; i++)
         {
             var dataKey      = binaryReader.ReadString();
             var dataPosition = binaryReader.ReadInt32();
             var dataLength   = binaryReader.ReadInt32();
             _index.Add(dataKey, new Entry(dataPosition, dataLength));
         }
     }
 }
        public T ReadData()
        {
            if (_memoryMappedFile == null)
            {
                GetMemoryMappedFile();
            }

            var mutex = GetMutex();

            using (var viewStream = _memoryMappedFile.CreateViewStream(offset: 0, size: _fileLength, access: MemoryMappedFileAccess.ReadWrite))
            {
                using (BinaryReader binaryReader = new BinaryReader(viewStream))
                {
                    var result = binaryReader.ReadBytes((int)viewStream.Length);

                    mutex.ReleaseMutex();

                    return(Deserialize(result));
                }
            }
        }
Esempio n. 15
0
            internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId)
            {
                Namespace = @namespace;
                Key       = key;

                _memoryMappedFile = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId), bufferSize);
                StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);

                ProfilerRequestsInformation = new EventWaitHandle(false, EventResetMode.ManualReset,
                                                                  MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId));

                InformationReadyForProfiler = new EventWaitHandle(false, EventResetMode.ManualReset,
                                                                  MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId));

                InformationReadByProfiler = new EventWaitHandle(false, EventResetMode.ManualReset,
                                                                MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId));

                DataCommunication       = new byte[bufferSize];
                PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned);
            }
Esempio n. 16
0
        /// <summary>
        /// Reads the memory-mapped file to discover servers.
        /// </summary>
        public IEnumerable <ValveIpcServerEntry> DiscoverServers()
        {
            _mutex.WaitOne();
            var list = new List <ValveIpcServerEntry>();

            using (var stream = _ipcFile.CreateViewStream())
            {
                do
                {
                    var entry = ValveIpcServerEntry.Parse(stream);
                    if (entry == null)
                    {
                        break;
                    }
                    list.Add(entry);
                } while (stream.Position < stream.Length);
            }

            _mutex.ReleaseMutex();
            return(list);
        }
Esempio n. 17
0
        public void CreateViewStreamAlignToPageSize()
        {
#if MONOTOUCH_WATCH
            int pageSize = 4096;
#elif MONOTOUCH
            // iOS bugs on ARM64 - bnc #27667 - apple #
            int pageSize = (IntPtr.Size == 4) ? Environment.SystemPageSize : 4096;
#else
            int pageSize = Environment.SystemPageSize;
#endif
            string f = Path.Combine(tempDir, "p-file");
            File.WriteAllBytes(f, new byte [pageSize * 2 + 1]);

            MemoryMappedFile mappedFile = MemoryMappedFile.CreateFromFile(f, FileMode.Open);

            MemoryMappedViewStream stream = mappedFile.CreateViewStream(pageSize * 2, 0, MemoryMappedFileAccess.ReadWrite);
#if !MONOTOUCH
            Assert.AreEqual(Environment.SystemPageSize, stream.Capacity);
#endif
            stream.Write(new byte [pageSize], 0, pageSize);
        }
Esempio n. 18
0
        public void run()
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("procfile", 10000))
            {
                newPrc.Start();
                Thread.Sleep(500);
                int i;

                while (true)
                {
                    using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                    {
                        sem.WaitOne();
                        BinaryReader reader = new BinaryReader(stream);
                        i = reader.ReadInt32();
                        i = (int)i / 254;
                        richTextBox1.Invoke(new Action(() => richTextBox1.Text += ("Pressed " + i.ToString()) + " button\n"));
                    }
                }
            }
        }
Esempio n. 19
0
 public FileSegment(MemoryMappedFile mmf, long offset, long length, MemoryMappedFileAccess access)
 {
     _mmf = Exceptions.CheckArgumentNull(mmf, "mmf");
     try
     {
         _length = length;
         if (_length == 0)
         {
             _stream = new MemoryStream();
         }
         else
         {
             _stream = mmf.CreateViewStream(offset, length, access);
         }
     }
     catch
     {
         _mmf.Dispose();
         throw;
     }
 }
Esempio n. 20
0
 public void VerifyCreateViewStreamException <EXCTYPE>(String strLoc, MemoryMappedFile mmf, long offset, long size, MemoryMappedFileAccess access) where EXCTYPE : Exception
 {
     iCountTestcases++;
     try
     {
         using (MemoryMappedViewStream view = mmf.CreateViewStream(offset, size, access))
         {
             iCountErrors++;
             Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
         }
     }
     catch (EXCTYPE)
     {
         //Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
     }
     catch (Exception ex)
     {
         iCountErrors++;
         Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
     }
 }
Esempio n. 21
0
		public ConnectImpl()
		{
			_onDataUpdatedEvent = new EventWaitHandle(true, EventResetMode.ManualReset, OnDataUpdatedEventName);
			_onWriteLockMutex = new Mutex(false, OnWriteLockMutexName);

			using (GetLock())
			{
				try
				{
					_memoryMappedFile = MemoryMappedFile.OpenExisting(MemoryMappedFileName);
				}
				catch (FileNotFoundException)
				{
					_memoryMappedFile = MemoryMappedFile.CreateNew(MemoryMappedFileName, MemoryMappedFileSize);
				}

				_memoryMappedViewAccessor = _memoryMappedFile.CreateViewAccessor();
				_memoryMappedViewStream = _memoryMappedFile.CreateViewStream();
				_memoryMappedViewHandle = _memoryMappedViewStream.SafeMemoryMappedViewHandle.DangerousGetHandle();
			}
		}
Esempio n. 22
0
 private BinaryWriter GenNewBinaryWriter(string fileName)
 {
     if (pckfileOpened == null)
     {
         if (filesize == 0)
         {
             filesize = new FileInfo(fileName).Length;
         }
         using (FileStream stream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
         {
             pckfileOpened = MemoryMappedFile.CreateFromFile(stream, null, 0, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.Inheritable, false);
         }
         viewStream = pckfileOpened.CreateViewStream(0, 0, MemoryMappedFileAccess.ReadWrite);
         return(new BinaryWriter(viewStream));
     }
     else
     {
         viewStream = pckfileOpened.CreateViewStream(0, 0, MemoryMappedFileAccess.ReadWrite);
         return(new BinaryWriter(viewStream));
     }
 }
    void IPCsetup()
    {
        TextChangedEvent    = new EventWaitHandle(false, EventResetMode.AutoReset, "ewhTabTipKeyboard");
        TextFieldClearEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "ewhTabTipClear");
        mmf = MemoryMappedFile.CreateOrOpen("hookTabTip", MMF_MAX_SIZE, MemoryMappedFileAccess.ReadWrite);
        TextFieldDataStream = mmf.CreateViewStream(0, MMF_VIEW_SIZE);

        var thread = new Thread(() =>
        {
            while (true)
            {
                TextChangedEvent.WaitOne();
                TextReader textReader = new StreamReader(TextFieldDataStream);
                ExternTextFieldData   = textReader.ReadLine();
                TextFieldDataStream.Seek(0, SeekOrigin.Begin);
            }
        });

        thread.IsBackground = true;
        thread.Start();
    }
Esempio n. 24
0
        private IntPtr Hook(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
        {
            if (msg != Command)
            {
                return(hwnd);
            }
            var stream = m_mappedRead.CreateViewStream();
            //读取字符长度
            int size = wparam.ToInt32();

            byte[] data = new byte[wparam.ToInt64()];
            stream.Read(data, 0, size);
            MemoryStream memory = new MemoryStream(data);
            BitmapImage  bitmap = new BitmapImage();

            bitmap.BeginInit();
            bitmap.StreamSource = memory;
            bitmap.EndInit();
            Revice(bitmap);
            return(hwnd);
        }
Esempio n. 25
0
        /* Initialize Mod Loader (DLL_PROCESS_ATTACH) */

        /// <summary>
        /// Initializes the mod loader.
        /// Returns the port on the local machine (but that wouldn't probably be used).
        /// </summary>
        public static int Initialize(IntPtr unusedPtr, int unusedSize)
        {
            // Write port as a Memory Mapped File, to allow Mod Loader's Launcher to discover the mod port.
            // (And to stop bootstrapper from loading loader again).
            int pid = Process.GetCurrentProcess().Id;

            _memoryMappedFile = MemoryMappedFile.CreateOrOpen(ServerUtility.GetMappedFileNameForPid(pid), sizeof(int));
            var view         = _memoryMappedFile.CreateViewStream();
            var binaryWriter = new BinaryWriter(view);

            binaryWriter.Write((int)0);

            // Setup Loader
            SetupLoader();

            // Only write port on completed initialization.
            // If port is 0, assume in loading state
            binaryWriter.Seek(-sizeof(int), SeekOrigin.Current);
            binaryWriter.Write(_server.Port);
            return(_server?.Port ?? 0);
        }
Esempio n. 26
0
        static void twórzPamięćWspółdzieloną()
        {
            Semaphore semaphore = new Semaphore(1, 1, @"Global\graŻabkaSemaphore");

            semaphore.WaitOne();
            ServiceController sc = GetServiceInstalled(ring1ServiceName);

            if (sc == null || sc.Status != ServiceControllerStatus.Running)
            {
                installAdminService();
            }
            sc.ExecuteCommand(131);
            semaphore.WaitOne();
            MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("Global\\graŻabkaMMF");

            byte[] buffer = new byte[1024];
            mmf.CreateViewStream(0, 1024).Read(buffer, 0, 1024);
            string val1 = (string)new BinaryFormatter().Deserialize(new MemoryStream(buffer));

            MessageBox.Show(val1);
        }
Esempio n. 27
0
        private void receiveMessage()
        {
            try {
                Console.WriteLine("Starting to lissen to MFF");
                using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("testmap")) {
                    while (true)
                    {
                        Mutex mutex = Mutex.OpenExisting("testmapmutex");
                        mutex.WaitOne();

                        using (MemoryMappedViewStream stream = mmf.CreateViewStream()) {
                            Console.WriteLine("Process A says: " + new BinaryReader(stream).ReadString());
                        }
                        mutex.ReleaseMutex();
                    }
                }
            }
            catch (FileNotFoundException ex) {
                Console.WriteLine("Receive message from MMF Failed: " + ex.Message);
            }
        }
Esempio n. 28
0
        public void Open(MemoryMappedFile mmf, string filePath = null)
        {
            this.FileName = filePath;

            using (MemoryMappedViewStream stream = mmf.CreateViewStream(
                       0L, 0L, MemoryMappedFileAccess.Read))
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    uint magic = reader.ReadUInt32();
                    if (stream.CanSeek && stream.Length < (magic ^ DictionaryMagicID)) //正確なサイズ取得ができないので不等号で代用
                    {
                        throw new MeCabInvalidFileException("dictionary file is broken", filePath);
                    }

                    this.Version = reader.ReadUInt32();
                    if (this.Version != DicVersion)
                    {
                        throw new MeCabInvalidFileException("incompatible version", filePath);
                    }

                    this.Type    = (DictionaryType)reader.ReadUInt32();
                    this.LexSize = reader.ReadUInt32();
                    this.LSize   = reader.ReadUInt32();
                    this.RSize   = reader.ReadUInt32();
                    uint dSize = reader.ReadUInt32();
                    uint tSize = reader.ReadUInt32();
                    uint fSize = reader.ReadUInt32();
                    reader.ReadUInt32(); //dummy

                    string charSet = StrUtils.GetString(reader.ReadBytes(32), Encoding.ASCII);
                    this.encoding = StrUtils.GetEncoding(charSet);

                    long offset = stream.Position;
                    this.da.Open(mmf, offset, dSize);
                    offset       += dSize;
                    this.tokens   = mmf.CreateViewAccessor(offset, tSize, MemoryMappedFileAccess.Read);
                    offset       += tSize;
                    this.features = mmf.CreateViewAccessor(offset, fSize, MemoryMappedFileAccess.Read);
                }
        }
Esempio n. 29
0
        public AudioPackage(string path, byte[] magicNumber)
        {
#if !WINDOWS
            path = path.Replace('\\', '/');
#endif
            file = MemoryMappedFile.CreateFromFile(path, FileMode.Open);
            view = file.CreateViewAccessor();
            view.SafeMemoryMappedViewHandle.AcquirePointer(ref filePointer);

            //
            // Magic Number:
            for (int i = 0; i < magicNumber.Length; i++)
            {
                if (filePointer[i] != magicNumber[i])
                {
                    ThrowError();
                }
            }

            //
            // Audio File Table:
            int tableLength = *(int *)(filePointer + magicNumber.Length);
            int tableStart  = magicNumber.Length + 4;
            vorbisPointer = filePointer + tableStart + tableLength;

            using (var stream = file.CreateViewStream(tableStart, tableLength))
            {
                using (BinaryReader br = new BinaryReader(new GZipStream(stream, CompressionMode.Decompress, true)))
                {
                    int count = br.ReadInt32();
                    offsets = new int[count + 1];                   // <- For simplicity, offsets[0] = 0 (start of first sound)
                    lookup  = new OrderedDictionary <string, int>(count);
                    for (int i = 0; i < count; i++)
                    {
                        lookup.Add(br.ReadString(), i);
                        offsets[i + 1] = br.ReadInt32();
                    }
                }
            }
        }
Esempio n. 30
0
        public Cars ReadCars()
        {
            using (var stream = carsInfoMMF.CreateViewStream())
            {
                using (var reader = new BinaryReader(stream))
                {
                    while (true)
                    {
                        var size   = Marshal.SizeOf(typeof(Cars));
                        var bytes  = reader.ReadBytes(size);
                        var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                        var data   = (Cars)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Cars));

                        int packetID = data.packetID;

                        if (packetID == -1)
                        {
                            handle.Free();

                            Thread.Sleep(10);

                            continue;
                        }

                        data = (Cars)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Cars));

                        handle.Free();

                        if (packetID == data.packetID)
                        {
                            return(data);
                        }
                        else
                        {
                            Thread.Sleep(10);
                        }
                    }
                }
            }
        }
 /// <summary>Creates and validates a view accessor and a view stream from the map.</summary>
 /// <param name="mmf">The map.</param>
 /// <param name="capacity">The capacity to use when creating the view.</param>
 /// <param name="access">The access to use when creating the view.</param>
 private static void CreateAndValidateViews(MemoryMappedFile mmf, long capacity, MemoryMappedFileAccess access)
 {
     using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(0, capacity, access))
     {
         ValidateMemoryMappedViewAccessor(accessor, capacity, access);
     }
     using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, capacity, access))
     {
         ValidateMemoryMappedViewStream(stream, capacity, access);
     }
 }