public string GetStringByIndex(int string_index) { if (string_index == -1) { return(null); } if (string_index < m_StringCache.Count) { var s = m_StringCache[string_index]; if (s != null) { return(s); } } while (m_StringCache.Count < string_index + 1) { m_StringCache.Add(null); } long tab_idx = m_MmapStringTablePos + (long)string_index * 8; long str_data_pos = m_MmapStringTablePos + m_MmapView.ReadUInt32(tab_idx); int str_len = m_MmapView.ReadInt32(tab_idx + 4); byte[] data = new byte[str_len]; m_MmapView.ReadArray(str_data_pos, data, 0, str_len); var result = Encoding.UTF8.GetString(data); m_StringCache[string_index] = result; return(result); }
static void P2() { //Thread.SpinWait(500000); MemoryMappedFile memoryMappedFile = null; while (memoryMappedFile == null) { try { memoryMappedFile = MemoryMappedFile.OpenExisting("MyMemoryMappedFile"); } catch (FileNotFoundException) { //CPU空转可以减少线程的上下文切换, 但是长时间空转挺废CPU的 Thread.SpinWait(5); //CPU消耗11% //会引起上下文切换, 也就是切换到内核模式并等待. 但是不太耗CPU //Thread.Sleep(1000); // CPU消耗0% Console.WriteLine("Enviroment.ProcessorCount: {0}", Environment.ProcessorCount); } } using (MemoryMappedViewAccessor FileMap = memoryMappedFile.CreateViewAccessor()) { while (FileMap.ReadInt32(0) != 5000) { Console.WriteLine(FileMap.ReadInt32(0)); Thread.SpinWait(50000000); } Console.WriteLine(FileMap.ReadInt32(0)); //int i = -1; //FileMap.Read<int>(4, out i); //Console.WriteLine("P2 Struct is : {0}", i); } }
public void CopyOnWrite() { const int MapLength = 256; foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength)) { using (mmf) { // Create a normal view, make sure the original data is there, then write some new data. using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.ReadWrite)) { Assert.Equal(0, acc.ReadInt32(0)); acc.Write(0, 42); } // In a CopyOnWrite view, verify the previously written data is there, then write some new data // and verify it's visible through this view. using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.CopyOnWrite)) { Assert.Equal(42, acc.ReadInt32(0)); acc.Write(0, 84); Assert.Equal(84, acc.ReadInt32(0)); } // Finally, verify that the CopyOnWrite data is not visible to others using the map. using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, MapLength, MemoryMappedFileAccess.Read)) { Assert.Equal(42, acc.ReadInt32(0)); } } } }
public static BitmapHeader GetHeader(MemoryMappedViewAccessor Reader, out long MMPosition) { MMPosition = 0; var header = new BitmapHeader(); header.Type = Encoding.ASCII.GetString(new byte[] { Reader.ReadByte(MMPosition) }); MMPosition++; header.Type += Encoding.ASCII.GetString(new byte[] { Reader.ReadByte(MMPosition) }); MMPosition++; header.FileSize = Reader.ReadInt32(MMPosition); MMPosition += 4; header.Reserved = Reader.ReadInt32(MMPosition); MMPosition += 4; header.Offset = Reader.ReadInt32(MMPosition); MMPosition += 4; header.BitmapInfoHeaderSize = Reader.ReadInt32(MMPosition); MMPosition += 4; return(header); }
public ItemData <int> ReadInt32(DeviceAddress address) { try { return(new ItemData <int>(accessor.ReadInt32(FindPosition(address)), 0, QUALITIES.QUALITY_GOOD)); } catch { return(new ItemData <int>(0, 0, QUALITIES.QUALITY_BAD)); } }
public async void ReadThread() { try { while (true) { while (receiverAccessor.ReadByte(0) != 1) { if (readCts.Token.IsCancellationRequested) { return; } Thread.Sleep(1);// await Task.Delay(1); } System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread DataReceived"); long position = 1; //CommandType var length = receiverAccessor.ReadInt32(position); position += sizeof(int); var typeNameArray = new byte[length]; receiverAccessor.ReadArray(position, typeNameArray, 0, typeNameArray.Length); position += typeNameArray.Length; System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread GetCommandType"); //RequestID length = receiverAccessor.ReadInt32(position); position += sizeof(int); var requestIdArray = new byte[length]; receiverAccessor.ReadArray(position, requestIdArray, 0, requestIdArray.Length); position += requestIdArray.Length; System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread GetRequestID"); //Data length = receiverAccessor.ReadInt32(position); position += sizeof(int); var dataArray = new byte[length]; receiverAccessor.ReadArray(position, dataArray, 0, dataArray.Length); System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread GetData"); //Write finish flag receiverAccessor.Write(0, (byte)0); System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread Write finish flag"); var commandType = PipeCommands.GetCommandType(Encoding.UTF8.GetString(typeNameArray)); var requestId = Encoding.UTF8.GetString(requestIdArray); var data = BinarySerializer.Deserialize(dataArray, commandType); System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread Parsed Type:{commandType.Name} requestId = {requestId}"); if (WaitReceivedDictionary.ContainsKey(requestId)) { System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread ContainsKey"); WaitReceivedDictionary[requestId] = data; } else { System.Diagnostics.Debug.WriteLine($"MemoryMappedFileBase ReadThread Raise Event"); ReceivedEvent?.Invoke(this, new DataReceivedEventArgs(commandType, requestId, data)); } } } catch (NullReferenceException) { } }
public override int GetInt() { var c = _accessor.ReadInt32(Position); Position += 4; //conform to how the index was written return(Number.FlipEndian(c)); }
public override int GetInt() { var littleEndian = _accessor.ReadInt32(Ix(NextGetIndex(4))); if (bigEndian) { return(Number.FlipEndian(littleEndian)); } return(littleEndian); }
public void ReadThread() { try { while (true) { while (receiverAccessor != null && receiverAccessor.ReadByte(0) != 1) { if (readCts.Token.IsCancellationRequested) { return; } Thread.Sleep(1); // await Task.Delay(1); } if (receiverAccessor == null) { return; } long position = 1; //CommandType var length = receiverAccessor.ReadInt32(position); position += sizeof(int); var typeNameArray = new byte[length]; receiverAccessor.ReadArray(position, typeNameArray, 0, typeNameArray.Length); position += typeNameArray.Length; //RequestID length = receiverAccessor.ReadInt32(position); position += sizeof(int); var requestIdArray = new byte[length]; receiverAccessor.ReadArray(position, requestIdArray, 0, requestIdArray.Length); position += requestIdArray.Length; //Data length = receiverAccessor.ReadInt32(position); position += sizeof(int); var dataArray = new byte[length]; receiverAccessor.ReadArray(position, dataArray, 0, dataArray.Length); //Write finish flag receiverAccessor.Write(0, (byte)0); var commandType = PipeCommands.GetCommandType(Encoding.UTF8.GetString(typeNameArray)); var requestId = Encoding.UTF8.GetString(requestIdArray); var data = BinarySerializer.Deserialize(dataArray, commandType); if (WaitReceivedDictionary.ContainsKey(requestId)) { WaitReceivedDictionary[requestId] = data; } else { ReceivedEvent?.Invoke(this, new DataReceivedEventArgs(commandType, requestId, data)); } } } catch (NullReferenceException) { } }
private IEnumerable <MatrixElement <T> > CachedMatrixElements() { for (long entryIdx = 0L; entryIdx < this.elementsCount; entryIdx++) { var offset = entryIdx * this.sizeOfEntryInBytes; var row = accessor.ReadInt32(offset); var column = accessor.ReadInt32(offset + sizeof(int)); T value; accessor.Read(offset + sizeof(int) + sizeof(int), out value); yield return(new MatrixElement <T>(row, column, value)); } }
public int GetInt(long position) { const long size = 4; if (position + size > _size) { _logger.Error($"Trying to read {size} bytes at {position:X} with just {_size - position} bytes left"); throw new OverflowException(); } var value = _va.ReadInt32(_offset + _position); return(value); }
public void setBit(int keycode, bool on) { var numIntinByte = (keycode / 32) * 4; var numBit = keycode % 32; var value = accessor.ReadInt32(numIntinByte); if (on) { accessor.Write(numIntinByte, value | (1 << numBit)); // set bit key } else { accessor.Write(numIntinByte, value & ~(1 << numBit)); // raz bit key } }
public string Read() { //Массив для сообщения из общей памяти char[] message; //Размер введенного сообщения int size; //Получение существующего участка разделяемой памяти //Параметр - название участка MemoryMappedFile sharedMemory = MemoryMappedFile.OpenExisting(Name); //Сначала считываем размер сообщения, чтобы создать массив данного размера //Integer занимает 4 байта, начинается с первого байта, поэтому передаем цифры 0 и 4 using (MemoryMappedViewAccessor reader = sharedMemory.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Read)) { size = reader.ReadInt32(0); } //Считываем сообщение, используя полученный выше размер //Сообщение - это строка или массив объектов char, каждый из которых занимает два байта //Поэтому вторым параметром передаем число символов умножив на из размер в байтах плюс //А первый параметр - смещение - 4 байта, которое занимает размер сообщения using (MemoryMappedViewAccessor reader = sharedMemory.CreateViewAccessor(4, size * 2, MemoryMappedFileAccess.Read)) { //Массив символов сообщения message = new char[size]; reader.ReadArray <char>(0, message, 0, size); } Console.WriteLine("Получено сообщение :"); Console.WriteLine(message); return(message.ToString()); }
/// <summary> /// Get or Generate unique transaction ID for function SendTransaction() /// </summary> internal int GetUniqueTransactionId() { if (mmf == null || accessor == null) { if (String.IsNullOrEmpty(WorkingFolder)) //WorkingFolder = Не определено. Создаем MMF в памяти { mmf = MemoryMappedFile.CreateOrOpen("UniqueID", 4096); } else //WorkingFolder определен. Открываем MMF с диска { string diskFileName = WorkingFolder + "\\" + "QUIKSharp.Settings"; try { mmf = MemoryMappedFile.CreateFromFile(diskFileName, FileMode.OpenOrCreate, "UniqueID", 4096); } catch { mmf = MemoryMappedFile.CreateOrOpen("UniqueID", 4096); } } accessor = mmf.CreateViewAccessor(); } int newId = accessor.ReadInt32(UniqueIdOffset); if (newId == 0) { newId = Convert.ToInt32(DateTime.Now.ToString("ddHHmmss")); } else { if (newId >= 2147483638) { newId = 100; } newId++; } try { accessor.Write(UniqueIdOffset, newId); } catch (Exception er) { Console.WriteLine("Неудачная попытка записини нового ID в файл MMF: " + er.Message); } return(newId); }
/* static void Main() * { * Application.EnableVisualStyles(); * Application.SetCompatibleTextRenderingDefault(false); * Application.Run(new Form1()); * }*/ static void Main(string[] str) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Globals.sharedMemory = MemoryMappedFile.CreateOrOpen("Bufer", 1000000); if (str.Length != 0 && str[0] == "TRUE") // если в параметрах было что-то передано - значит в разделяемой памяти находятся техпроцессы { int size; // размер передаваемого сообщения byte[] byteArray; // считываем размер сообщения using (MemoryMappedViewAccessor reader = Globals.sharedMemory.CreateViewAccessor(0, 4)) { size = reader.ReadInt32(0); reader.Dispose(); } // считываем сообщение using (MemoryMappedViewAccessor reader = Globals.sharedMemory.CreateViewAccessor(4, size)) { byteArray = new byte[size]; reader.ReadArray <byte>(0, byteArray, 0, size); reader.Dispose(); } XmlSerializer xmlSer = new XmlSerializer(typeof(TechList)); MemoryStream stream = new MemoryStream(byteArray); TechList Tlist = (TechList)(xmlSer.Deserialize(stream)); Application.Run(new Form1(Tlist)); return; } Application.Run(new Form1()); }
public static int GetSavedPort(string appName) { MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(appName, 4); MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); return(accessor.ReadInt32(0)); }
private static string ReadMemory() // чтение shared memory { try { char[] message; int size; MemoryMappedFile sharedMemory = MemoryMappedFile.OpenExisting("MemoryFile"); using (MemoryMappedViewAccessor reader = sharedMemory.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Read)) { size = reader.ReadInt32(0); } using (MemoryMappedViewAccessor reader = sharedMemory.CreateViewAccessor(4, size * 2, MemoryMappedFileAccess.Read)) { message = new char[size]; reader.ReadArray(0, message, 0, size); } return(new string(message)); } catch (Exception ex) { MessageBox.Show("Произошла ошибка, возможно вы забыли запустить сервер\n" + ex.Message, "", MessageBoxButton.OK, MessageBoxImage.Error); return(null); } }
public static void Decode(out AllocateAddressEvent ev, MemoryMappedViewAccessor view, ref long pos) { ev.Address = view.ReadUInt64(pos); ev.Size = view.ReadUInt64(pos + 8); ev.NameStringIndex = view.ReadInt32(pos + 16); pos += 20; }
private void Reader() { try { Console.WriteLine("reader"); _mapCreated.Wait(); Console.WriteLine("reader starting"); using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting(MapName, MemoryMappedFileRights.Read)) { using (MemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor(0, 10000, MemoryMappedFileAccess.Read)) { _dataWrittenEvent.Wait(); Console.WriteLine("reading can start now"); for (int i = 0; i < 400; i += 4) { int result = accessor.ReadInt32(i); Console.WriteLine($"reading {result} from position"); } } } } catch (Exception e) { Console.WriteLine(e.Message); } }
//读取器 private static void Reader() { try { Console.WriteLine("reader"); _mapCreated.Wait(); Console.WriteLine("reader starting"); //简历内存映射文件 using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting(MAPNAME, MemoryMappedFileRights.Read)) { //通过视图读取器打开共享内存映射文件 using (MemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor(0, 10000, MemoryMappedFileAccess.Read)) { //等待写入完成 _dataWrittenEvent.Wait(); Console.WriteLine("reading can start now"); //开始读取 for (int i = 0; i < 400; i += 4) { int result = accessor.ReadInt32(i); Console.WriteLine($"reading {result} from position {i}"); } } } } catch (Exception ex) { Console.WriteLine($"reader {ex.Message}"); } }
/// <summary> /// 从内存获取文本 /// </summary> /// <param name="Name">名字 确认内存的位置</param> /// <returns>获取的文本</returns> public static string GETStringFromMemory(string Name) { //创建异步阻塞 MemoryMappedFile lockmmf = MemoryMappedFile.CreateOrOpen("lpsdb" + Name + "lock", 1, MemoryMappedFileAccess.ReadWrite); MemoryMappedViewAccessor lockmmva = lockmmf.CreateViewAccessor(); while (lockmmva.ReadBoolean(0)) { Thread.Sleep(10); } lockmmva.Write(0, true); //正常操作 MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(Name); MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor(); int len = mmva.ReadInt32(0); char[] buff = new char[len]; mmva.ReadArray <char>(4, buff, 0, len); mmva.Dispose(); mmf.Dispose(); lockmmva.Write(0, false); lockmmva.Dispose(); lockmmf.Dispose(); return(new string(buff)); }
public AudioClip Load(string memory_name) { Debug.Log("CutEffectLoader.Load"); // Open shared memory MemoryMappedFile share_mem = MemoryMappedFile.OpenExisting(memory_name); MemoryMappedViewAccessor accessor = share_mem.CreateViewAccessor(); // Write data to shared memory int size = accessor.ReadInt32(0); byte[] data = new byte[size]; accessor.ReadArray <byte>(sizeof(int), data, 0, data.Length); Debug.Log("DataSize = " + size); // Dispose resource accessor.Dispose(); share_mem.Dispose(); clip = WavUtility.ToAudioClip(data, 0, "wav"); Debug.Log("clip = " + clip.loadState); return(clip); }
//读取数据 private void Reader() { try { Console.WriteLine("reader"); //读取器首先等待创建内存映射文件 _mapCreated.Wait(); Console.WriteLine("reader starting"); //打开内存映射文件 using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting( MAPNAME, MemoryMappedFileRights.Read)) { //创建一个视图访问器 using (MemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor( 0, 10000, MemoryMappedFileAccess.Read)) { //等待设置_dataWritenEvent _dataWritenEvent.Wait(); Console.WriteLine("reading can start now"); for (int i = 0; i < 400; i += 4) { int result = accessor.ReadInt32(i); Console.WriteLine($"reading {result} from position {i}"); } } } } catch (Exception ex) { Console.WriteLine("reader " + ex.Message); } }
private void CalculateNextStart(MemoryMappedViewAccessor accessor, int seqSize, long writerPosition) { long nextStartpoint = 32, nextBlockSize = 0; //do //{ // var prevBlockSize = accessor.ReadInt32(nextStartpoint); // nextStartpoint += prevBlockSize + _int32Size; //} while (nextStartpoint > writerPosition); while (nextBlockSize < seqSize) { var prevBlockSize = accessor.ReadInt32(nextStartpoint); nextStartpoint += prevBlockSize + _int32Size; nextBlockSize += prevBlockSize + _int32Size; } //if (nextStartpoint >= Size) { // nextStartpoint = 32; //} NextStart = nextStartpoint; }
/// <summary> /// 读取器首先等待创建内存映射文件,再使用MemoryMappedFile.0penExisting打开它。 /// 读取器只需要映射的读取权限。之后,与前面的写入器类似,创建一个视图访问器。 /// 在读取数据之前,等待设置_dataWrittenEvent()读取类似于写入, /// 因为也要提供应该访问数据的位置,但是不同的Read方法,如Readlnt32,用于读取不同的数据类型 /// </summary> private static void Reader() { try { Console.WriteLine("reader"); _mapCreated.Wait(); Console.WriteLine("reader开始"); using (MemoryMappedFile mappedFile = MemoryMappedFile.OpenExisting(MAPNAME, MemoryMappedFileRights.Read)) { using (MemoryMappedViewAccessor accessor = mappedFile.CreateViewAccessor(0, 10000, MemoryMappedFileAccess.Read)) { _dataWrittenEvent.Wait(); Console.WriteLine("现在可以开始读取"); for (int i = 0; i < 400; i += 4) { int result = accessor.ReadInt32(i); Console.WriteLine($"从位置{i}上读取了{result}"); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
// вставка техпроцессов из разделяемой памяти в системный грид private void ToolStripMenuItemPasteFromMappedMemory_Click(object sender, EventArgs e) { int size; // размер передаваемого сообщения byte[] byteArray; // считываем размер сообщения using (MemoryMappedViewAccessor reader = Globals.sharedMemory.CreateViewAccessor(0, 4, MemoryMappedFileAccess.Read)) { size = reader.ReadInt32(0); reader.Dispose(); } // считываем сообщение using (MemoryMappedViewAccessor reader = Globals.sharedMemory.CreateViewAccessor(4, size, MemoryMappedFileAccess.Read)) { byteArray = new byte[size]; reader.ReadArray <byte>(0, byteArray, 0, size); reader.Dispose(); } XmlSerializer xmlSer = new XmlSerializer(typeof(TechList)); MemoryStream stream = new MemoryStream(byteArray); TechList Tlist = (TechList)(xmlSer.Deserialize(stream)); foreach (Technology tech in Tlist.list) { Globals.AddTechnology(tech); } }
private void ReaderThread(object stateInfo) { while (started) { // Checks if there is something to read. var dataAvailable = view.ReadBoolean(ReadPosition + DATA_AVAILABLE_OFFSET); if (dataAvailable) { // Checks how many bytes to read. int availableBytes = view.ReadInt32(ReadPosition + DATA_LENGTH_OFFSET); var bytes = new byte[availableBytes]; // Reads the byte array. int read = view.ReadArray <byte>(ReadPosition + DATA_OFFSET, bytes, 0, availableBytes); // Sets the flag used to signal that there aren't available data anymore. view.Write(ReadPosition + DATA_AVAILABLE_OFFSET, false); // Sets the flag used to signal that data has been read. view.Write(ReadPosition + READ_CONFIRM_OFFSET, true); MemoryMappedDataReceivedEventArgs args = new MemoryMappedDataReceivedEventArgs(bytes, read); operation.Post(callback, args); } Thread.Sleep(500); } }
private void ReadThreadMethod() { while (State == ResonanceComponentState.Connected) { if (_thisSemaphore == null) { if (!EventWaitHandle.TryOpenExisting(_thisSemaphoreName, out _thisSemaphore)) { Thread.Sleep(100); continue; } } _thisSemaphore.WaitOne(); if (State != ResonanceComponentState.Connected) { return; } int length = _accessor.ReadInt32(0); byte[] data = new byte[length]; _accessor.ReadArray <byte>(4, data, 0, data.Length); if (length > 0) { OnDataAvailable(data); } else { Thread.Sleep(100); } } }
static Telemetry ReadAllValues(MemoryMappedViewAccessor accessor, int buffOffset, VarHeader[] varHeaders) { var result = new Telemetry(); var maps = new Dictionary <VarType, Func <int, object> >() { { VarType.irInt, (offset) => accessor.ReadInt32(offset) }, { VarType.irBitField, (offset) => accessor.ReadInt32(offset) }, { VarType.irDouble, (offset) => accessor.ReadDouble(offset) }, { VarType.irBool, (offset) => accessor.ReadBoolean(offset) }, { VarType.irFloat, (offset) => accessor.ReadSingle(offset) } }; var arryMaps = new Dictionary <VarType, Func <int, int, object> >() { { VarType.irInt, (size, offset) => GetArrayData <int>(accessor, size, offset) }, { VarType.irBitField, (size, offset) => GetArrayData <int>(accessor, size, offset) }, { VarType.irDouble, (size, offset) => GetArrayData <double>(accessor, size, offset) }, { VarType.irFloat, (size, offset) => GetArrayData <float>(accessor, size, offset) }, { VarType.irBool, (size, offset) => GetArrayData <bool>(accessor, size, offset) } }; for (var i = 0; i < varHeaders.Length; i++) { var varHeader = varHeaders[i]; var offset = buffOffset + varHeader.offset; if (varHeader.type == VarType.irChar) { throw new NotSupportedException(); } object value; if (varHeader.count != 1) { value = arryMaps[varHeader.type](varHeader.count, offset); } else { value = maps[varHeader.type](offset); } result.Add(varHeader.name, value); } return(result); }
public override string ReadData() { int dataLength = viewAccessor.ReadInt32(0); var data = new byte[dataLength]; viewAccessor.ReadArray <byte>(4, data, 0, dataLength); return(Encoding.UTF8.GetString(data)); }