void ReadImageData(MemoryMappedViewAccessor view) { int ids = GetImageDataSize(); ImageData = new byte[ids]; view.ReadArray(GetImageDataStart(), ImageData, 0, ImageData.Length); }
void ReadColorMap(MemoryMappedViewAccessor view) { int cms = GetColorMapSize(); ColorMap = new byte[cms]; view.ReadArray(GetColorMapStart(), ColorMap, 0, ColorMap.Length); }
internal T[] ReadArray <T>(long position, int count) where T : struct { T[] array = new T[count]; _accessor.ReadArray(position, array, 0, count); return(array); }
private string ReadIPCClassNameMMF() { MemoryMappedFile mmf = null; MemoryMappedViewAccessor mma = null; try { byte[] buffer = new byte[128]; mmf = MemoryMappedFile.OpenExisting("DS4Windows_IPCClassName.dat"); mma = mmf.CreateViewAccessor(0, 128); mma.ReadArray(0, buffer, 0, buffer.Length); return(ASCIIEncoding.ASCII.GetString(buffer)); } catch (Exception) { // Eat all exceptions } finally { if (mma != null) { mma.Dispose(); } if (mmf != null) { mmf.Dispose(); } } return(null); }
private string WaitAndReadIPCResultDataMMF(EventWaitHandle ipcNotifyEvent) { if (ipcResultDataMMA != null) { // Wait until the inter-process-communication (IPC) result data is available and read the result try { // Wait max 10 secs and if the result is still not available then timeout and return "empty" result if (ipcNotifyEvent == null || ipcNotifyEvent.WaitOne(10000)) { int strNullCharIdx; byte[] buffer = new byte[256]; ipcResultDataMMA.ReadArray(0, buffer, 0, buffer.Length); strNullCharIdx = Array.FindIndex(buffer, byteVal => byteVal == 0); return(ASCIIEncoding.ASCII.GetString(buffer, 0, (strNullCharIdx <= 1 ? 1 : strNullCharIdx))); } } catch (Exception) { /* Eat all exceptions because errors here are not fatal for DS4Win */ } } return(String.Empty); }
static T[] GetArrayData <T>(MemoryMappedViewAccessor accessor, int size, int offset) where T : struct { var data = new T[size]; accessor.ReadArray <T>(offset, data, 0, size); return(data); }
public void Read() { InitializeViewAccessor(); if (_memoryMappedAccessor == null) { return; } byte [] rawData = new byte[Marshal.SizeOf(typeof(T))]; _memoryMappedAccessor.ReadArray(0, rawData, 0, rawData.Length); T createdObject; IntPtr reservedMemPtr = IntPtr.Zero; try { reservedMemPtr = Marshal.AllocHGlobal(rawData.Length); Marshal.Copy(rawData, 0, reservedMemPtr, rawData.Length); createdObject = (T)Marshal.PtrToStructure(reservedMemPtr, typeof(T)); } finally { if (reservedMemPtr != IntPtr.Zero) { Marshal.FreeHGlobal(reservedMemPtr); } } Data = createdObject; }
public static byte[] read_byte_MMF(string path_file) { byte[] bufferItem = new byte[] { }; if (File.Exists(path_file)) { MemoryMappedFileSecurity mSec = new MemoryMappedFileSecurity(); mSec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); using (FileStream stream = new FileStream(path_file, FileMode.OpenOrCreate)) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(stream, null, stream.Length, MemoryMappedFileAccess.ReadWrite, mSec, HandleInheritability.None, true)) { using (MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor()) { bufferItem = new byte[mmfReader.Capacity]; mmfReader.ReadArray <byte>(0, bufferItem, 0, bufferItem.Length); } } } } return(bufferItem); }
private static long InnerReadCacheNotifyData(long lastTicks, MemoryMappedViewAccessor accessor, CacheNotifyDataMapInfo mapInfo, List <CacheNotifyData> result) { int itemSize = Marshal.SizeOf(typeof(CacheNotifyDataMapItem)); long returnTicks = lastTicks; long startPointer = Marshal.SizeOf(typeof(CacheNotifyDataMapInfo)); for (int i = 0; i < CacheNotifyDataMapInfo.CacheDataItemCount; i++) { CacheNotifyDataMapItem item; accessor.Read(startPointer, out item); if (item.Ticks > lastTicks) { if (item.Ticks > returnTicks) { returnTicks = item.Ticks; } byte[] data = new byte[item.Size]; accessor.ReadArray(startPointer + itemSize, data, 0, (int)item.Size); CacheNotifyData cnd = CacheNotifyData.FromBuffer(data); result.Add(cnd); } startPointer += itemSize + CacheNotifyDataMapInfo.CacheDataBlockSize; } return(returnTicks); }
public string Read() { //Массив для сообщения из общей памяти char[] message; //Размер введенного сообщения int size; //Получение существующего участка разделяемой памяти //Параметр - название участка MemoryMappedFile sharedMemory = MemoryMappedFile.OpenExisting("MemoryFile"); //Сначала считываем размер сообщения, чтобы создать массив данного размера //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); }
}//end function public static T read_MMF <T>(string path_file) where T : struct { T item = new T(); if (File.Exists(path_file)) { byte[] bufferItem; MemoryMappedFileSecurity mSec = new MemoryMappedFileSecurity(); mSec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); using (FileStream stream = new FileStream(path_file, FileMode.OpenOrCreate)) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(stream, null, stream.Length, MemoryMappedFileAccess.ReadWrite, mSec, HandleInheritability.None, true)) { using (MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor()) { bufferItem = new byte[mmfReader.Capacity]; mmfReader.ReadArray <byte>(0, bufferItem, 0, bufferItem.Length); } } } int objsize = Marshal.SizeOf(typeof(T)); IntPtr buff = Marshal.AllocHGlobal(objsize); Marshal.Copy(bufferItem, 0, buff, objsize); item = (T)Marshal.PtrToStructure(buff, typeof(T)); Marshal.FreeHGlobal(buff); } return(item); }
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); var args = new DataReceivedEventArgs(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); } } }
private byte[] GetConvertedValue(MemoryMappedViewAccessor source, bool wholeArray = false) { int bytesToRead = wholeArray ? MaxDataSize : DataSize; int elemsToRead = wholeArray ? MaxArrayLength : ArrayLength; byte[] value = new byte[bytesToRead]; source.ReadArray(Position, value, 0, bytesToRead); if (_ConvertMode != ConvertMode.NONE) { for (int i = 0; i < elemsToRead; i++) { float temp = ToSingle(value, i * ElementSize); if (_ConvertMode == ConvertMode.MULTIPLY) { if (_Multiplier != null) { temp *= (float)_Multiplier; } } if (_ConvertMode == ConvertMode.CHANGE_UNIT) { if (converterFunc != null) { temp = converterFunc(temp); } } byte[] newValue = GetBytes(temp); Array.Copy(newValue, 0, value, i * ElementSize, ElementSize); } } if (_CastToInt != CastMode.NONE) { for (int i = 0; i < elemsToRead; i++) { float temp = ToSingle(value, i * ElementSize); int castedTemp = 0; switch (_CastToInt) { case CastMode.FLOOR: castedTemp = (int)Math.Floor(temp); break; case CastMode.ROUND: castedTemp = (int)Math.Round(temp); break; case CastMode.CEIL: castedTemp = (int)Math.Ceiling(temp); break; } byte[] newValue = GetBytes(castedTemp); Array.Copy(newValue, 0, value, i * ElementSize, ElementSize); } } return(value); }
public static T[] ReadArray <T>(this MemoryMappedViewAccessor accessor, int offset, int count) where T : struct { var array = new T[count]; accessor.ReadArray(offset, array, 0, count); return(array); }
public override void Copy(long offset, byte[] bytes) { // Although not explicitly marked as thread safe, from // reviewing the source code, these operations appear to // be thread safe as long as only read operations are // being done. _view.ReadArray(offset, bytes, 0, bytes.Length); }
private void ProcessResponse(EventCaller eventCaller, MemoryMappedViewAccessor accessor) { byte[] data = new byte[eventCaller.MessageLength]; accessor.ReadArray(eventCaller.OffsetPosition, data, 0, eventCaller.MessageLength); _dataTestbasicHaywire = data.GetString(); }
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)); }
public byte[] Read(long position, int length) { lock (file) { byte[] output = new byte[length]; file.ReadArray <byte>(position, output, 0, length); return(output); } }
void ReadImageID(MemoryMappedViewAccessor view) { ImageID = new byte[IDLength]; if (IDLength > 0) { view.ReadArray(18, ImageID, 0, IDLength); } }
public virtual byte[] GetByteValue(MemoryMappedViewAccessor source, bool wholeArray) { int bytesToRead = wholeArray ? MaxDataSize : DataSize; byte[] value = new byte[bytesToRead]; source.ReadArray(Position, value, 0, bytesToRead); return(value); }
private string IPC_Quick_Send(string Ipc_str) { if (bIPC_Open == false) { IPC_Open(); } if (bIPC_Open) { byte[] WriteByte; string Ipc_tx = "s" + cnt_Send + Ipc_str; WriteByte = ASCIIEncoding.ASCII.GetBytes(Ipc_tx); evt.Set(); // -------------------------------------------------------------------------- // 1024 byte dummy send.. byte[] DummyWrite; DummyWrite = new byte[1024]; m_hMemoryAccessor.WriteArray <byte>(0, DummyWrite, 0, DummyWrite.Length); Thread.Sleep(2); // -------------------------------------------------------------------------- // command send m_hMemoryAccessor.WriteArray <byte>(0, WriteByte, 0, WriteByte.Length); cnt_Send++; if (cnt_Send == 10) { cnt_Send = 0; } Thread.Sleep(10); byte[] bReadData = new byte[1024]; //To make sure during iteration these params will not be changed const int PNC_ACK_Sleep_ms = 20; const int PNC_ACK_Loop_Max_local = 100; for (int Ack = 0; Ack < PNC_ACK_Loop_Max_local; Ack++) { Thread.Sleep(PNC_ACK_Sleep_ms); m_hMemoryAccessor.ReadArray <byte>(0, bReadData, 0, bReadData.Length); if (bReadData[0] == 'r') { break; } else if (bReadData[0] == 'm') { string tta = Encoding.Default.GetString(bReadData) + "\r\n"; richtextbox.AppendText(tta); return(tta); } } evt.Reset(); } return(string.Empty); }
public static void Add <T>(BTree whichTree, object objectToAdd, int objectToAddID, string fileDirectoryPlusName) { byte[] objectArray = ObjectToByteArray(objectToAdd); int tempindex; if (whichTree.isEmpty()) { tempindex = -1; } else { tempindex = whichTree.getLast(); } // Get a handle to an existing memory mapped file using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileDirectoryPlusName, FileMode.Open, "mmf", (tempindex + 2) * objectArray.Length)) // (UP) Here we created a filefrom a memoryMappedFile that it's capacity is (tempindex + 2) times larger than objectArray.Length //HERE WE SHOULD THINK ABOUT IT!!!! { // Create a view accessor from which to read the data using (MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor()) { //Then to access the file created from MemoryMappedFile ,we use MemoryMappedViewAccessor byte[] buffer = new byte[objectArray.Length]; //HERE WE Have an array of bytes to read the data to it //With length = objectArray.Length //HERE IS THE TRICK //TO SAVE THE DATA IN FILE ==>> We navigate over the file to find the null place to save the data for (int index = 0; ; index++) { if (mmfReader.CanRead) { mmfReader.ReadArray <byte>(index * objectArray.Length, buffer, 0, buffer.Length); //Posiiton is the startPoint of reading the data //The unit of reading data is our buffer arraysize //COUNTER = buffer.Length //Because we want to read from start to end of the unit,We set OFFSET to 0 T temp = (T)ByteArrayToObject(buffer); if (temp == null) //HERE we found the empty place , so we save data their { whichTree.put(objectToAddID, index); //We save the index in our BTREE mmfReader.WriteArray <byte>(index * objectArray.Length, objectArray, 0, buffer.Length); //DATA is written to File return; } } else { return; } } } } }//DECODED SUCCESSFULLY
private string ReadString(ref int offset) { int size = ReadInt32(ref offset); var buffer = new byte[size]; int read = _memoryMappedViewAccessor.ReadArray(offset, buffer, 0, size); if (read != size) throw new NotImplementedException(); offset += size * ByteOffset; return Encoding.ASCII.GetString(buffer); }
public static string ReadString(this MemoryMappedViewAccessor obj, int pos) { var len = obj.ReadInt32(pos); var chr = new char[len]; obj.ReadArray <char>(pos + 4, chr, 0, len); return(new string(chr)); }
public T[] ReadArray <T>() where T : struct { int length = Read <Int32>(); T[] values = new T[length]; accessor.ReadArray <T>(currentLocation, values, 0, values.Length); currentLocation += Marshal.SizeOf(typeof(T)) * values.Length; return(values); }
private Byte[] InternalRead() { using MemoryMappedViewAccessor accessor = _memoryMappedFile.CreateViewAccessor(); Int32 length = accessor.ReadInt32(0); Byte[] data = new Byte[length]; accessor.ReadArray(sizeof(Int32), data, 0, length); return(data); }
public byte[] GetBytes(int offset, int len) { byte[] buffer = new byte[len]; fileAccessor.ReadArray(offset, buffer, 0, len); string bufferStr = Encoding.ASCII.GetString(buffer); buffer = Encoding.ASCII.GetBytes(bufferStr); return(buffer); }
public byte[] GetContents(AlfEntry entry) { using MemoryMappedViewAccessor accessor = AlfFile.CreateViewAccessor(entry.Offset, entry.Size, MemoryMappedFileAccess.Read); var data = new byte[entry.Size]; accessor.ReadArray(0, data, 0, entry.Size); return(data); }
/// <summary> /// Инициализирует структуры данных информацией из файла БД /// </summary> /// <param name="fileName">Путь к файлу БД</param> /// <param name="holder">Хранилище структур данных БД</param> public void Load(string fileName, DataHolder holder) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, FileMode.Open, "a", 0, MemoryMappedFileAccess.Read)) { using (MemoryMappedViewAccessor mmfa = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read)) { mmfa.Read(0, out holder.Header); holder.IpTable = new IpRecord[holder.Header.records]; holder.LocationTable = new LocationRecord[holder.Header.records]; holder.LocationByNameIndex = new int[holder.Header.records]; mmfa.ReadArray(holder.Header.offset_ranges, holder.IpTable, 0, holder.Header.records); mmfa.ReadArray(holder.Header.offset_locations, holder.LocationTable, 0, holder.Header.records); mmfa.ReadArray(holder.Header.offset_cities, holder.LocationByNameIndex, 0, holder.Header.records); } } }