/// <summary> /// Gets current value of _writePointer from shared memory. /// Must be called from a synchronized context! /// </summary> private void loadWritePointer() { if (_writer) { throw new InvalidOperationException("Writing MemoryMappedQueue must not read its property (write pointer) from the memory mapped file."); } using (MemoryMappedViewAccessor pointerAccessor = _pointersFile.CreateViewAccessor(0, 3 * _pointerSize)) { long newWritePointer, newOverflowWritePointer; pointerAccessor.Read <long>(_pointerSize, out newWritePointer); pointerAccessor.Read <long>(_pointerSize * 2, out newOverflowWritePointer); _writePointer = newWritePointer; _overflowWritePointer = newOverflowWritePointer; _usingOverflowWritePointer = _overflowWritePointer > -1; } }
public void EnableWatchDog(bool en) { if (_commAccessLock.WaitOne(100)) { _commAccessor.Read(_statusOffset, out _status); _driverTimestamp = _status.DriverTime; if (_driverTimestamp != _prevDriverTimestamp) { DriverTime = DateTime.Now; } _prevDriverTimestamp = _driverTimestamp; _status.EnableWatchDog = en ? 1 : 0; _commAccessor.Write(_statusOffset, ref _status); _commAccessLock.ReleaseMutex(); } }
public T Read <T>() where T : struct { #if NET45 int size = Marshal.SizeOf(typeof(T)); #else int size = Marshal.SizeOf <T>(); #endif if (_offset + size > _capacity) { Resize(size); } T result; #if NETSTANDARD1_3 byte[] rawData = new byte[size]; Read(rawData, 0, size); unsafe { fixed(byte *rawDataPtr = rawData) { result = Marshal.PtrToStructure <T>((IntPtr)rawDataPtr); } } #else _view.Read(_offset, out result); #endif _offset += size; return(result); }
public TRootObject Read() { TRootObject value; view.Read(0, out value); return(value); }
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 MyDataStructure2 Get(string trace) { MyDataStructure2 data; //Mutex mget = new Mutex(); //string str = DateTime.Now.ToString("dd-MMM-yy hh:mm:ss.fff"); //Console.Write(trace + ") before Get Mutex " + str + "\n"); _mset.WaitOne(); try { _accessor.Read <MyDataStructure2>(0, out data); //accessor.Dispose(); } finally { _mset.ReleaseMutex(); //str = DateTime.Now.ToString("dd-MMM-yy hh:mm:ss.fff"); //Console.Write(trace + ") after Get Mutex " + str + "\n"); } return(data); }
static public void Unsafe() { File.WriteAllBytes("unsafe.bin", new byte[100]); var data = new Data { X = 123, Y = 456 }; using MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("unsafe.bin"); using MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(); accessor.Write(0, ref data); accessor.Read(0, out data); Console.WriteLine(data.X + " " + data.Y); // 123 456 unsafe { byte *pointer = null; try { accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer); int *intPointer = (int *)pointer; Console.WriteLine(*intPointer); // 123 } finally { if (pointer != null) { accessor.SafeMemoryMappedViewHandle.ReleasePointer(); } File.Delete("unsafe.bin"); } } }
internal Node GetNode(UInt32 offset) { Node node; accessor.Read(nodeSize * offset, out node); return(node); }
private CVMSection InternalReadSection(MemoryMappedViewAccessor accessor, ref long pos) { CVMSection section; accessor.Read(ref pos, 4, out section.tag); accessor.ReadBE(ref pos, out section.length); return(section); }
public T Read <T>() where T : struct { T value; accessor.Read <T>(currentLocation, out value); currentLocation += Marshal.SizeOf(typeof(T)); return(value); }
public T this[int index] { get { var offset = this.GetOffset(index); T result; accessor.Read(offset, out result); return(result); } set { var offset = this.GetOffset(index); accessor.Write(offset, ref value); } }
public MappedLibrary(String path) { file = MemoryMappedFile.CreateFromFile(path); accessor = file.CreateViewAccessor(); Node rootSpec; accessor.Read(0, out rootSpec); root = new LibraryNode(this, rootSpec); }
public bool WriteString(string msg, MemoryMappedViewAccessor memoryMappedViewAccessor) { //Console.WriteLine(">WriteString"); //ハンドシェイクカウンタチェック memoryMappedViewAccessor.Read(SHARED_MEMORY_ADDRESS_COUNTER_SEND, out byte sendcnt); memoryMappedViewAccessor.Read(SHARED_MEMORY_ADDRESS_COUNTER_HANDSHAKE, out byte handshakecnt); //Console.WriteLine("sendcnt:" + sendcnt); //Console.WriteLine("handshakecnt:" + handshakecnt); //ハンドシェイクと送信が一致していない = 相手が受け取れていない if (sendcnt != handshakecnt) { //送信中止 //Console.WriteLine("送信中止: 相手待機中"); return(false); } //送信データ更新 byte[] stringArray = ASCIIEncoding.ASCII.GetBytes(msg); if (stringArray.Length > SHARED_MEMORY_STRING_AREA_SIZE) { Console.WriteLine("例外: 文字列が大きすぎる"); throw new ArgumentOutOfRangeException("string too large"); } memoryMappedViewAccessor.Write(SHARED_MEMORY_ADDRESS_SIZE_OF_STRING_AREA + 0, (byte)((stringArray.Length >> 0) & 0xFF)); memoryMappedViewAccessor.Write(SHARED_MEMORY_ADDRESS_SIZE_OF_STRING_AREA + 1, (byte)((stringArray.Length >> 8) & 0xFF)); memoryMappedViewAccessor.Write(SHARED_MEMORY_ADDRESS_SIZE_OF_STRING_AREA + 2, (byte)((stringArray.Length >> 16) & 0xFF)); memoryMappedViewAccessor.Write(SHARED_MEMORY_ADDRESS_SIZE_OF_STRING_AREA + 3, (byte)((stringArray.Length >> 24) & 0xFF)); memoryMappedViewAccessor.WriteArray(SHARED_MEMORY_ADDRESS_STRING_AREA, stringArray, 0, stringArray.Length); //送信データカウンタ更新 sendcnt = (byte)((((int)sendcnt) + 1) & 0xFF); memoryMappedViewAccessor.Write(SHARED_MEMORY_ADDRESS_COUNTER_SEND, (byte)sendcnt); //Console.WriteLine("+sendcnt:" + sendcnt); //送信成功 //Console.WriteLine("送信完了: " + msg); //Console.WriteLine("<WriteString\n"); return(true); }
void VectorDisplay() { long sizeChar = sizeof(char); long sizeF = sizeof(float); long sizeQ = Marshal.SizeOf(typeof(Quaternion)); long jf; info vec; vec.name = new char[charLength]; vectorNow = menuItem.GetComponent <MenuItem>().vectorIndex; timeNow = menuItem.GetComponent <MenuItem>().timeNow; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(files[timeNow])) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { //矢量绘制 jf = sizeMesh[areaNow] + sizeScalar[areaNow] * scalarNum + sizeVector[areaNow] * vectorNow; accessor.ReadArray <char>(jf, vec.name, 0, charLength); jf += sizeChar * charLength; accessor.Read <float>(jf, out vec.max); jf += sizeF; accessor.Read <float>(jf, out vec.min); jf += sizeF; tMax1.text = "Max:" + vec.max; tMin1.text = "Min:" + vec.min; for (int i = 0; i < meshNum; i++) { if (meshVNum[i] != 0) { accessor.ReadArray <Quaternion>(jf, quats[i], 0, meshVNum[i]); jf += sizeQ * meshVNum[i]; accessor.ReadArray <float>(jf, values[i], 0, meshVNum[i]); jf += sizeF * meshVNum[i]; Quaternion q = objects.GetComponent <Transform>().rotation; for (int j = 0; j < meshVNum[i]; ++j) { preArraw[i][j].GetComponent <Transform>().rotation = q * quats[i][j]; preArraw[i][j].GetComponent <Transform>().localScale = new Vector3(1, 1, 1) * 0.1f * values[i][j]; } } } } } }
// Use this for initialization void Start() { long sizeI = sizeof(int); long sizeV = Marshal.SizeOf(typeof(Vector3)); long sizeF = sizeof(float); long jf = 0; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file)) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { accessor.Read <int>(jf, out meshNum); jf += sizeI; pre = new GameObject[meshNum]; meshVNum = new int[meshNum]; meshTNum = new int[meshNum]; value = new float[meshNum]; for (int j = 0; j < meshNum; j++) { accessor.Read <int>(jf, out meshVNum[j]); jf += sizeI; Vector3[] vertices = new Vector3[meshVNum[j]]; accessor.Read <int>(jf, out meshTNum[j]); jf += sizeI; int[] triangles = new int[meshTNum[j]]; accessor.ReadArray <Vector3>(jf, vertices, 0, meshVNum[j]); jf += sizeV * meshVNum[j]; accessor.ReadArray <int>(jf, triangles, 0, meshTNum[j]); jf += sizeI * meshTNum[j]; accessor.Read <float>(jf, out value[j]); jf += sizeF; //创建预设体,赋予顶点和拓扑 pre[j] = (GameObject)Instantiate(Resources.Load("Prefabs/Pres/PreTriangle")); pre[j].transform.parent = GetComponent <Transform>(); Mesh mesh = pre[j].GetComponent <MeshFilter>().mesh; mesh.Clear(); mesh.vertices = vertices; mesh.triangles = triangles; mesh.RecalculateNormals(); } } } }
private static void Main(string[] args) { Console.Write("请输入共享内存公用名(默认:testmap):"); string shareName = Console.ReadLine(); if (string.IsNullOrEmpty(shareName)) { shareName = "testmap"; } using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(shareName, 1024000, MemoryMappedFileAccess.ReadWrite)) { bool mutexCreated; //进程间同步 var mutex = new Mutex(true, "testmapmutex", out mutexCreated); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) //创建文件内存视图流 { var writer = new BinaryWriter(stream); for (int i = 0; i < 5; i++) { writer.Write(i); Console.WriteLine("{0}位置写入流:{0}", i); } } mutex.ReleaseMutex(); Console.WriteLine("启动状态服务,按【回车】读取共享内存数据"); Console.ReadLine(); mutex.WaitOne(); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { var reader = new BinaryReader(stream); for (int i = 0; i < 10; i++) { Console.WriteLine("{1}位置:{0}", reader.ReadInt32(), i); } } using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor(1024, 10240)) { int colorSize = Marshal.SizeOf(typeof(ServiceMsg)); ServiceMsg color; for (int i = 0; i < 50; i += colorSize) { accessor.Read(i, out color); Console.WriteLine("{1}\tNowTime:{0}", new DateTime(color.NowTime), color.Id); } } mutex.ReleaseMutex(); } Console.WriteLine("测试: 我是 即时通讯 - 消息服务 我启动啦!!!"); Console.ReadKey(); }
public Bar(Position Pos, Color NormalBack, Color NormalFore, Color FocusedBack, Color FocusedFore, Font Font) { Text = "BTWM-EXCLUDED windwenu"; BackColor = NormalBack; ForeColor = NormalFore; this.Font = Font; // Make windmenu appear on focused screen output = Screen.PrimaryScreen; foreach (Screen scr in Screen.AllScreens) { if (scr.Bounds.Contains(Cursor.Position)) { output = scr; } } pos = Pos; DoubleBuffered = true; // Reduce flickering on redraw TopMost = true; // Draw on top of everything barBack = NormalBack; barFore = new SolidBrush(NormalFore); selBack = new SolidBrush(FocusedBack); selFore = new SolidBrush(FocusedFore); FormBorderStyle = FormBorderStyle.None; ShowInTaskbar = false; // Retreive program list: try { MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("windmenu", MemoryMappedFileRights.Read); MemoryMappedViewAccessor va = mmf.CreateViewAccessor(0, 8, MemoryMappedFileAccess.Read); long sizeData; va.Read(0, out sizeData); va.Dispose(); va = mmf.CreateViewAccessor(8, sizeData, MemoryMappedFileAccess.Read); byte[] data = new byte[sizeData]; va.ReadArray(0, data, 0, (int)sizeData); va.Dispose(); mmf.Dispose(); programList = Encoding.Unicode.GetString(data).Split('|'); } catch (Exception) { throw new Exception("Communication error with the server.\nTry killing the server and starting it again."); } suggestions = new List <string>(); }
public static bool Read(string filename) { using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(filename)) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { accessor.Read(1, out bool boolean); return(boolean); } } }
public static Node Read(MemoryMappedViewAccessor view, long offset = 0) { #if DOTNETSTANDARD_1_3 return(new Node(view.ReadInt64(offset), view.ReadInt64(offset + sizeof(long)))); #else Node result; view.Read(offset, out result); return(result); #endif }
void ScalarDisplay() { panelColor.SetActive(true); long sizeChar = sizeof(char); long sizeF = sizeof(float); long sizeC = Marshal.SizeOf(typeof(Color)); long jf; info sca; sca.name = new char[charLength]; scalarNow = menuItem.GetComponent <MenuItem>().scalarIndex; timeNow = menuItem.GetComponent <MenuItem>().timeNow; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(files[timeNow])) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { //标量绘制 jf = sizeMesh[areaNow] + sizeScalar[areaNow] * scalarNow; accessor.ReadArray <char>(jf, sca.name, 0, charLength); jf += sizeChar * charLength; accessor.Read <float>(jf, out sca.max); jf += sizeF; accessor.Read <float>(jf, out sca.min); jf += sizeF; tMax.text = "Max:" + sca.max; tMin.text = "Min:" + sca.min; for (int i = 0; i < meshNum; i++) { if (meshVNum[i] != 0) { pre[i].GetComponent <MeshRenderer>().materials[1].SetFloat("_AlphaScale", 1); accessor.ReadArray <Color>(jf, colors[i], 0, meshVNum[i]); jf += sizeC * meshVNum[i]; Mesh mesh = pre[i].GetComponent <MeshFilter>().mesh; mesh.colors = colors[i]; } } } } }
private void CreateBomb(Object source, ElapsedEventArgs e) { Entity entity; int curship = shiprandom.Next(0, ShipCount); int count = 0; for (int i = 0; i < used; i += entitySize) { acc.Read(i, out entity); string name = Marshal.PtrToStringAnsi(entity.TypeA); if (name.Contains("ship")) { if (count == curship) { dynamic bomb = Activator.CreateInstance(BombT); BombT.GetField("Manager").SetValue(bomb, this); globalShip[0] = (short)(entity.X + 3); globalShip[1] = entity.Y; BombT.GetProperty("Offset").SetValue(bomb, Draw("bomb")); BombT.InvokeMember("Action", System.Reflection.BindingFlags.InvokeMethod, null, bomb, null); return; } else { count++; } } } }
public Index(MemoryMappedFile file) { this.file = file; var metadataSize = Marshal.SizeOf(typeof(Metadata)); metadataAccessor = file.CreateViewAccessor(0, metadataSize); metadataAccessor.Read(0, out metadata); // BST bstPosition = metadataSize; bstNodeSize = Marshal.SizeOf(typeof(IndexEntry)); }
/// <summary> /// <para>Reads Vector3 struct through MemoryMappedViewAccessor at given position.</para> /// <para>Position is updated to accomodate size of Vector3.</para> /// </summary> public static Vector3 MmvaReadVector3(MemoryMappedViewAccessor accessor, ref long position) { var result = new Vector3(); for (var i = 0; i < 3; ++i) { accessor.Read(position, out float tmp); result[i] = tmp; position += sizeof(float); } return(result); }
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)); } }
protected override void OnStartup(StartupEventArgs e) { string[] commandLineArgs = System.Environment.GetCommandLineArgs(); try { bool createdNew = false; _instanceMutex = new Mutex(true, mutexName, out createdNew); #region Open Existing App if (!createdNew) { IntPtr hWnd = System.IntPtr.Zero; lock (typeof(MainWindow)) { using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(mmfName, MemoryMappedFileRights.Read)) { using (MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read)) { mmfReader.Read <IntPtr>(0, out hWnd); } } } //WindowActivator.Activate(hWnd); Application.Current.Shutdown(); return; } #endregion lock (typeof(MainWindow)) { sharedMemory = MemoryMappedFile.CreateNew(mmfName, 8, MemoryMappedFileAccess.ReadWrite); } } catch (Exception ex) { MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace + "\n\n", "Exception thrown"); Application.Current.Shutdown(); return; } finally { } base.OnStartup(e); //var t = new Dictionary<int, string>(); //var i = t.Keys.FirstOrDefault(ind => ind == 3); }
/// <summary> /// Peek ahead bytes but do not chnage the seek pointer in sequential access /// </summary> /// <param name="position">The position in the file at which to begin reading /// relative to the current position in the file. Default is 0</param> /// <param name="count">The number of bytes to read. Default 1.</param> /// <returns>A byte array</returns> public LayoutModel <TLayoutType> PeekStructure <TLayoutType>(int count = 1, long position = 0) where TLayoutType : struct { LayoutModel <TLayoutType> model = new LayoutModel <TLayoutType>(); using (MemoryMappedViewAccessor tempPeek = this.MemoryFile.CreateViewAccessor(position, count, MemoryMappedFileAccess.Read)) { TLayoutType fileData; tempPeek.Read(position, out fileData); model.SetData(fileData); } return(model); }
public List <JsonObj> ReadMem() { HWiNFOMemory = new _HWiNFO_SHARED_MEM(); try { mmf = MemoryMappedFile.OpenExisting(HWiNFO_SHARED_MEM_FILE_NAME, MemoryMappedFileRights.Read); accessor = mmf.CreateViewAccessor(0L, Marshal.SizeOf(typeof(_HWiNFO_SHARED_MEM)), MemoryMappedFileAccess.Read); accessor.Read(0L, out HWiNFOMemory); return(ReadSensorNames()); } catch { return(new List <JsonObj>()); } }
private void Button_Scan_Next_Click(object sender, EventArgs e) { UInt64 FirstAddress = 0; UInt64 LastAddress = 0; if (CurrentAddressAccessor.Capacity > 0) { CurrentAddressAccessor.Read(0, out FirstAddress); } if (CurrentAddressAccessor.Capacity > 0) { CurrentAddressAccessor.Read(CurrentAddressAccessor.Capacity - (Int64)DataTypeSize.Int64, out LastAddress); } if (!ScanButtonShared(true, FirstAddress, LastAddress)) { return; } Canceled = false; Button_Scan_Abort.Enabled = true; ListView_Address.SelectedIndices.Clear(); }
/// <summary> /// 플롯형 데이터의 인덱서 입니다. /// </summary> /// <param name="idx">반환 할 데이터의 인덱스</param> /// <returns>인덱스에 위치한 값</returns> public double this[int idx] { get { var position = getPosition(idx); double readValue; _memView.Read(position, out readValue); return(readValue); } set { var position = getPosition(idx); _memView.Write(position, value); } }
public T this[long index] { set { if (index < 0 || index > numberOfElements) { throw new ArgumentOutOfRangeException(); } accesor.Write <T>(index * elementSize, ref value); } get { if (index < 0 || index > numberOfElements) { throw new ArgumentOutOfRangeException(); } T value = default(T); accesor.Read <T>(index * elementSize, out value); return(value); } }