public static Dictionary <string, byte[]> GetResourceDict(string filePath) { Dictionary <string, byte[]> dict = new Dictionary <string, byte[]>(); byte[] bytes = File.ReadAllBytes(filePath); Assembly assembly = Assembly.Load(bytes); string[] resourcesName = assembly.GetManifestResourceNames(); foreach (string resourceName in resourcesName) { using (System.IO.UnmanagedMemoryStream stream = (System.IO.UnmanagedMemoryStream)(assembly.GetManifestResourceStream(resourceName))) { ResourceManager rm = new ResourceManager("app", assembly); ResourceSet resourceSet = null; try { resourceSet = rm.GetResourceSet(System.Threading.Thread.CurrentThread.CurrentCulture, true, true); } catch (MissingManifestResourceException) { return(null); } foreach (DictionaryEntry entry in resourceSet) { string key = entry.Key.ToString(); byte[] contentBytes = entry.Value as byte[]; dict[key] = contentBytes; } } } return(dict); }
unsafe internal void UpdateSecondaryNativeProperties( IList <PropertyInitializer> properties, System.IO.UnmanagedMemoryStream stream) { if (_localToWorldAttribute != null) { // we have to build a "local to world" transform, and push that through. var trans = DomNode.As <ITransformable>(); if (trans != null) { var localToWorld = trans.LocalToWorld; properties.Add( GameEngine.CreateInitializer( _localToWorldAttribute.PropertyId, stream.PositionPointer, typeof(float), 16, false)); for (int c = 0; c < 16; ++c) { ((float *)stream.PositionPointer)[c] = localToWorld[c]; } stream.Position += sizeof(float) * 16; } } if (_visibleHierarchyAttribute != null) { var visible = DomNode.As <IVisible>(); if (visible != null) { uint d = Convert.ToUInt32(visible.Visible); SetBasicProperty(_visibleHierarchyAttribute.PropertyId, d, properties, stream); *(uint *)stream.PositionPointer = d; stream.Position += sizeof(uint); } } }
public void PlaySound(System.IO.UnmanagedMemoryStream fileName) { SoundPlayer sound = new SoundPlayer(fileName); sound.LoadAsync(); sound.Play(); }
internal ResourceReader(Stream stream, Dictionary<string, ResourceLocator> resCache) { this._resCache = resCache; this._store = new BinaryReader(stream, Encoding.UTF8); this._ums = stream as UnmanagedMemoryStream; this.ReadResources(); }
public unsafe void Write(Stream value) { if (value.Length > _availableLength) throw new ArgumentException("Value is too long."); var buffer = new byte[4096]; var lengthToWrite = value.Length; while (lengthToWrite > 0) { using (var stream = new UnmanagedMemoryStream(_currentPointer.Value.Ptr, _currentPointer.Value.AvailableLength, _currentPointer.Value.AvailableLength, FileAccess.ReadWrite)) { do { var read = value.Read(buffer, 0, Math.Min(buffer.Length, _currentPointer.Value.AvailableLength)); stream.Write(buffer, 0, read); lengthToWrite -= read; _currentPointer.Value.AvailableLength -= read; } while (_currentPointer.Value.AvailableLength > 0 && lengthToWrite > 0); _currentPointer = _currentPointer.Next; } } }
public override unsafe void callback(string md5, IntPtr msg_buf, uint msg_len) { if (md5 != expected_md5sum) { Debug.WriteLine("Got unexpected md5sum message expected {0} got {1} dropping message", expected_md5sum, md5); return; } T o; using (var unsafe_reader = new System.IO.UnmanagedMemoryStream((byte *)msg_buf, msg_len, msg_len, FileAccess.Read)) { var binary_reader = new BinaryReader(unsafe_reader); o = read_func(binary_reader); } try { callback_action(o); } catch (Exception e) { Debug.WriteLine("Error occured in callback method {0}", e.ToString()); return; } }
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); } } }
public void GetData_ReturnArrayOfStructs() { unsafe { short[] @in = new short[50]; for (int i = 0; i < 50; i++) { @in[i] = (short)i; } int inSize = 100; // 50 x 2 bytes per short // Allocate a block of unmanaged memory and return an IntPtr object. IntPtr memIntPtr = Marshal.AllocHGlobal(inSize); // Get a byte pointer from the IntPtr object. byte* memBytePtr = (byte*)memIntPtr.ToPointer(); var stream = new UnmanagedMemoryStream(memBytePtr, inSize); // Set the data stream.SetData(@in); // Get the data back out short[] @out = stream.GetData<short>(); Assert.AreEqual(@in.Length, @out.Length); for (int i = 0; i < 50; i++) { Assert.AreEqual(@in[i], @out[i]); } } }
public override int ReadPrefix(string shortSha, out ObjectId id, out UnmanagedMemoryStream data, out ObjectType objectType) { id = null; data = null; objectType = default(ObjectType); ObjectId matchingKey; int ret = ExistsPrefix(shortSha, out matchingKey); if (ret != (int)ReturnCode.GIT_OK) { return ret; } ret = Read(matchingKey, out data, out objectType); if (ret != (int)ReturnCode.GIT_OK) { return ret; } id = matchingKey; return (int)ReturnCode.GIT_OK; }
// Constructor public MumbleLink() { unsafe { _memSize = Marshal.SizeOf(typeof(MumbleLinkedMemory)); _mappedFile = NativeMethods.OpenFileMapping(FileMapAccess.FileMapRead, false, Name); if (_mappedFile == IntPtr.Zero) { _mappedFile = NativeMethods.CreateFileMapping(IntPtr.Zero, IntPtr.Zero, FileMapProtection.PageReadWrite, 0, _memSize, Name); if (_mappedFile == IntPtr.Zero) { throw new Exception("Unable to create file Mapping"); } } _mapView = NativeMethods.MapViewOfFile(_mappedFile, FileMapAccess.FileMapRead, 0, 0, _memSize); if (_mapView == IntPtr.Zero) { throw new Exception("Unable to map view of file"); } _buffer = new byte[_memSize]; _bufferHandle = GCHandle.Alloc(_buffer, GCHandleType.Pinned); byte* p = (byte*)_mapView.ToPointer(); _unmanagedStream = new UnmanagedMemoryStream(p, _memSize, _memSize, FileAccess.Read); } }
public unsafe static Image LoadFromMemory(IntPtr pSource, int size, bool makeACopy, GCHandle? handle) { using (var memoryStream = new UnmanagedMemoryStream((byte*)pSource, size)) using (var bitmap = (Bitmap)BitmapFactory.DecodeStream(memoryStream)) { var bitmapData = bitmap.LockPixels(); var image = Image.New2D(bitmap.Width, bitmap.Height, 1, PixelFormat.B8G8R8A8_UNorm, 1, bitmap.RowBytes); #if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES // Directly load image as RGBA instead of BGRA, because OpenGL ES devices don't support it out of the box (extension). CopyMemoryBGRA(image.PixelBuffer[0].DataPointer, bitmapData, image.PixelBuffer[0].BufferStride); #else Utilities.CopyMemory(image.PixelBuffer[0].DataPointer, bitmapData, image.PixelBuffer[0].BufferStride); #endif bitmap.UnlockPixels(); if (handle != null) handle.Value.Free(); else if (!makeACopy) Utilities.FreeMemory(pSource); return image; } }
public UnmanagedMemory() : base() { this._localBuffer = null; this._unmanagedStream = null; this._bufferSizeInBytes = new Int32(); this._memoryBlock = IntPtr.Zero; return; }
//Adds the sound we want to play public void Add(int index, UnmanagedMemoryStream stream) { _soundStreams[index] = new SoundStream(stream); _audioBuffers[index] = new AudioBuffer(); _audioBuffers[index].Stream = _soundStreams[index].ToDataStream(); _audioBuffers[index].AudioBytes = (int) _soundStreams[index].Length; _audioBuffers[index].Flags = BufferFlags.EndOfStream; _sourceVoices[index] = new SourceVoice(_audio, _soundStreams[index].Format); }
public WriterWorkItem(FileStream fileStream, UnmanagedMemoryStream memStream, MD5 md5) { _fileStream = fileStream; _memStream = memStream; _workingStream = (Stream)fileStream ?? memStream; Buffer = new MemoryStream(8192); BufferWriter = new BinaryWriter(Buffer); MD5 = md5; }
public static void playSoundEffect(UnmanagedMemoryStream soundFile) { if (soundFlag == true) { Stream stream = soundFile; sp = new System.Media.SoundPlayer(stream); sp.Play(); } }
unsafe private static void SetBasicProperty <T>( uint propId, T obj, IList <PropertyInitializer> properties, System.IO.UnmanagedMemoryStream stream) { properties.Add(GameEngine.CreateInitializer( propId, stream.PositionPointer, typeof(T), 1, false)); }
public List <SolidWorksNameSpace> GetData() { if (Context.SolidWorksNameSpacesData != null) { return(Context.SolidWorksNameSpacesData); } SolidWorksNameSpacesData = new List <SolidWorksNameSpace>(); Assembly assembly = Assembly.GetAssembly(typeof(Context)); string resourceName = assembly.GetName().Name + ".g"; ResourceManager rm = new ResourceManager(resourceName, assembly); using (ResourceSet set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true)) { //遍历资源集 foreach (DictionaryEntry item in set) { if (!item.Key.ToString().Contains("SolidWorks.Interop".ToLower())) { continue; } try { //使用资源流 using (System.IO.UnmanagedMemoryStream UmMS = item.Value as System.IO.UnmanagedMemoryStream) { if (UmMS.CanRead) { //反序列化 using (StreamReader sr = new StreamReader(UmMS)) { string XmlStr = sr.ReadToEnd(); SolidWorksNameSpace NameSpace = new SolidWorksNameSpace(); NameSpace = XmlHelper.Deserialize((NameSpace), XmlStr); if (NameSpace != null) { SolidWorksNameSpacesData.Add(NameSpace); } } //var NameSpace = XmlHelper.Deserialize(typeof(SolidWorksNameSpace), UmMS) as SolidWorksNameSpace; //if (NameSpace != null) //{ // SolidWorksNameSpacesData.Add(NameSpace); //} } Console.WriteLine(item.Key.ToString()); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } return(SolidWorksNameSpacesData); }
public void DisposeMemStream() { var memStream = _memStream; if (memStream != null) { memStream.Dispose(); _memStream = null; } }
private void on_trace_data_collected(cef_trace_client_t* self, byte* fragment, UIntPtr fragment_size) { CheckSelf(self); using (var stream = new UnmanagedMemoryStream(fragment, (long)fragment_size)) { OnTraceDataCollected(stream); } }
/// <summary> /// Play notes from wave files for each instrument radio button /// </summary> /// <param name="instrumentKeyboardRadioButton"></param> /// <param name="instrumentNote"></param> void PlayNoteOnInstrument(RadioButton instrumentKeyboardRadioButton, System.IO.UnmanagedMemoryStream instrumentNote) { if (instrumentKeyboardRadioButton.Checked) { System.Media.SoundPlayer sound = new System.Media.SoundPlayer(instrumentNote); sound.Load(); sound.Play(); } }
public void Add(int index, UnmanagedMemoryStream sourceStream) { streams[index] = new SoundStream(sourceStream); buffers[index] = new AudioBuffer(); buffers[index].Stream = streams[index].ToDataStream(); buffers[index].AudioBytes = (int)streams[index].Length; buffers[index].Flags = BufferFlags.EndOfStream; voices[index] = new SourceVoice(audio, streams[index].Format); }
/// <summary> /// Read raw binary data. /// </summary> private int read(cef_read_handler_t* self, void* ptr, int size, int n) { ThrowIfObjectDisposed(); long length = size * n; using (var m_stream = new UnmanagedMemoryStream((byte*)ptr, length, length, FileAccess.Write)) { return this.Read(m_stream, size, n); } }
/// <summary> /// Write raw binary data. /// </summary> private int write(cef_write_handler_t* self, /*const*/ void* ptr, int size, int n) { ThrowIfObjectDisposed(); long length = size * n; using (var m_stream = new UnmanagedMemoryStream((byte*)ptr, size * n, size * n, FileAccess.Read)) { return this.Write(m_stream, size, n); } }
private UIntPtr read(cef_read_handler_t* self, void* ptr, UIntPtr size, UIntPtr n) { CheckSelf(self); var length = (long)size * (long)n; using (var stream = new UnmanagedMemoryStream((byte*)ptr, length, length, FileAccess.Write)) { return (UIntPtr)Read(stream, length); } }
/// <summary> /// Gets the image file machine type. /// </summary> /// <param name="buffer">Memory buffer representing native library.</param> /// <returns>Image file machine type.</returns> public static unsafe ushort GetImageFileMachineType(byte[] buffer) { fixed(byte *ptr = buffer) { using(UnmanagedMemoryStream ums = new UnmanagedMemoryStream(ptr, buffer.Length)) { return GetImageFileMachineType(ums); } } }
public void Close() { Marshal.FreeHGlobal(this._memoryBlock); this._unmanagedStream.Close(); this._unmanagedStream = null; this._memoryBlock = IntPtr.Zero; return; }
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); } } }
private void on_download_data(cef_urlrequest_client_t* self, cef_urlrequest_t* request, void* data, UIntPtr data_length) { CheckSelf(self); var m_request = CefUrlRequest.FromNative(request); using (var stream = new UnmanagedMemoryStream((byte*)data, (long)data_length)) { OnDownloadData(m_request, stream); } }
/// <summary> /// A portion of the file contents have been received. This method will /// be called multiple times until the download is complete. Return /// |true| to continue receiving data and |false| to cancel. /// </summary> private int received_data(cef_download_handler_t* self, void* data, int data_size) { ThrowIfObjectDisposed(); var m_stream = new UnmanagedMemoryStream((byte*)data, data_size, data_size, FileAccess.Read); var handled = this.ReceivedData(m_stream); m_stream.Dispose(); return handled ? 1 : 0; }
unsafe public static void DEV9writeDMA8Mem(byte *memPointer, int size) { try { System.IO.UnmanagedMemoryStream pMem = new System.IO.UnmanagedMemoryStream(memPointer, size, size, System.IO.FileAccess.Read); dev9.DEV9_WriteDMA8Mem(pMem, size); } catch (Exception e) { CLR_PSE_PluginLog.MsgBoxErrorTrapper(e); throw; } }
/// <summary> /// Serialize item to destination /// </summary> /// <typeparam name="T">item type</typeparam> /// <param name="item">item</param> /// <param name="ms">memory stream</param> /// <returns>The number of bytes written or negative if insufficient space</returns> public static int Serialize <T>(T item, System.IO.UnmanagedMemoryStream ms) { byte *dst = ms.PositionPointer; int avail = (int)Math.Max(ms.Length - ms.Position, int.MaxValue); int result = Serialize(item, dst, avail); if (result > 0) { ms.PositionPointer = dst + result; } return(result); }
public static unsafe Bitmap DownloadEvf(IntPtr Camera) { uint success; Bitmap _bmp, _newbmp; UnmanagedMemoryStream ums; // while (true) { IntPtr _stream = IntPtr.Zero; IntPtr _image = new IntPtr(); IntPtr _imageData = new IntPtr(); uint _imageLen; int _width = 500, _height = 330; _newbmp = new Bitmap(_width, _height); success = EDSDK.EdsCreateMemoryStream(0, out _stream); if (success == EDSDK.EDS_ERR_OK) { success = EDSDK.EdsCreateEvfImageRef(_stream, out _image); } if (success == EDSDK.EDS_ERR_OK) { success = EDSDK.EdsDownloadEvfImage(Camera, _image); } if (success == EDSDK.EDS_ERR_OK) { EDSDK.EdsGetPointer(_stream, out _imageData); EDSDK.EdsGetLength(_stream, out _imageLen); ums = new UnmanagedMemoryStream((byte*)_imageData.ToPointer(), _imageLen, _imageLen, FileAccess.Read); _bmp = new Bitmap(ums, true); _newbmp = new Bitmap(_bmp, _width, _height); //LiveViewBox是定义的一个pictureBox 控件 //LiveViewBox1.Image = _newbmp; } if (_stream != IntPtr.Zero) { EDSDK.EdsRelease(_stream); _stream = IntPtr.Zero; } if (_image != IntPtr.Zero) { EDSDK.EdsRelease(_image); _image = IntPtr.Zero; } } return _newbmp; }
public void flush() { lock (this) { if (callCount == 0) return; //Insert the EOF binaryWriter.Write((int)StreamInstructionTypes.STREAM_INSTRUCTION_EOF); IntPtr incomingPointer; unsafe { InstanceManager.sync(instancePtr, bufferPointer, &incomingPointer); UnmanagedMemoryStream strm = new UnmanagedMemoryStream((byte*)incomingPointer, maxCallLenght, maxCallLenght, FileAccess.Read); BinaryReader reader = new BinaryReader(strm); UInt32 instruction; bool EOF = false; while (!EOF) { try { instruction = reader.ReadUInt32(); } catch(Exception eek) { Console.WriteLine("EOF is invalid!"); Console.WriteLine(eek.ToString()); break; } switch(instruction) { case (int)StreamInstructionTypes.STREAM_INSTRUCTION_CALL: String cmd = StreamHelper.ReadString(reader); handleEvent(cmd, reader); break; case (int)StreamInstructionTypes.STREAM_INSTRUCTION_EOF: EOF = true; break; } } resetBuffers(); } } }
private int read_response(cef_resource_handler_t* self, void* data_out, int bytes_to_read, int* bytes_read, cef_callback_t* callback) { CheckSelf(self); var m_callback = CefCallback.FromNative(callback); using (var m_stream = new UnmanagedMemoryStream((byte*)data_out, bytes_to_read, bytes_to_read, FileAccess.Write)) { int m_bytesRead; var result = ReadResponse(m_stream, bytes_to_read, out m_bytesRead, m_callback); *bytes_read = m_bytesRead; return result ? 1 : 0; } }
static Stream GetMonoTouchData (string name) { int size = 0; IntPtr data = monotouch_timezone_get_data (name, ref size); if (size <= 0) throw new TimeZoneNotFoundException (); unsafe { var s = new UnmanagedMemoryStream ((byte*) data, size); s.Closed += delegate { Marshal.FreeHGlobal (data); }; return s; } }
public static void PlaySoundResource(UnmanagedMemoryStream unmanagedMemoryStream) { try { // http://msdn.microsoft.com/en-us/library/3w5b27z4.aspx SoundPlayer player = new SoundPlayer(); unmanagedMemoryStream.Seek(0, SeekOrigin.Begin); player.Stream = unmanagedMemoryStream; player.Play(); } catch (Exception x) { Console.WriteLine("PlaySoundResource: Error trying to access or play the resource: " + x.Message); } }
public ResourceReader(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable")); } this._resCache = new Dictionary<string, ResourceLocator>(FastResourceComparer.Default); this._store = new BinaryReader(stream, Encoding.UTF8); this._ums = stream as UnmanagedMemoryStream; this.ReadResources(); }
/// <summary> /// Set |substitute_data| to the replacement for the data in |data| if /// data should be modified. /// </summary> private void process_data(cef_content_filter_t* self, /*const*/ void* data, int data_size, cef_stream_reader_t** substitute_data) { ThrowIfObjectDisposed(); var m_stream = new UnmanagedMemoryStream((byte*)data, data_size, data_size, FileAccess.Read); CefStreamReader m_substitute_data; this.ProcessData(m_stream, out m_substitute_data); if (m_substitute_data != null) { *substitute_data = m_substitute_data.GetNativePointerAndAddRef(); } m_stream.Dispose(); }
public void Constructor1 () { UnmanagedMemoryStream ums = new UnmanagedMemoryStream(mem_byteptr, length); Assert.AreEqual ((long) length, ums.Capacity, "#1"); Assert.AreEqual ((long) length, ums.Length, "#2"); Assert.AreEqual (0L, ums.Position, "#3"); ums.Position = (length-2); Assert.AreEqual ((long)(length - 2), ums.Position, "#4"); ums.Position = 0; ums.Seek(3L, SeekOrigin.Begin); Assert.AreEqual (3L, ums.Position, "#5"); Assert.IsTrue (ums.CanRead, "#6"); Assert.IsFalse (ums.CanWrite, "#7"); ums.Close(); }
public void WriteAll() { if ((this._localBuffer != null) && (this._localBuffer.Length > 0)) { this._bufferSizeInBytes = UnicodeEncoding.Unicode.GetByteCount(this._localBuffer); this._memoryBlock = Marshal.AllocHGlobal(this._bufferSizeInBytes); this._unmanagedStream = new System.IO.UnmanagedMemoryStream((( Byte * )this._memoryBlock.ToPointer()), this._bufferSizeInBytes, this._bufferSizeInBytes, FileAccess.ReadWrite); this._unmanagedStream.Write(UnicodeEncoding.Unicode.GetBytes(this._localBuffer)); } ; return; }
public override int Read(ObjectId id, out UnmanagedMemoryStream data, out ObjectType objectType) { using (var tx = _env.NewTransaction(TransactionFlags.Read)) { ReadResult readResult1 = tx.State.GetTree(tx, Index).Read(tx, id.Sha); Debug.Assert(readResult1 != null); var bf = new BinaryFormatter(); var meta = (ObjectDescriptor) bf.Deserialize(readResult1.Reader.AsStream()); objectType = meta.ObjectType; data = Allocate(meta.Length); ReadResult readResult2 = tx.State.GetTree(tx, Objects).Read(tx, id.Sha); readResult2.Reader.CopyTo(data); } return (int)ReturnCode.GIT_OK; }
public unsafe static void OnFillBuffer(byte * pData, long lDataLen) { Trace.WriteLine(++i + ": _EncodeInternal: " + lDataLen); using (var f = File.Open("dump.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { f.Seek(0, SeekOrigin.End); using (var b = new BinaryWriter(f)) { b.Write((int)lDataLen); using (UnmanagedMemoryStream ms = new UnmanagedMemoryStream(pData, lDataLen)) { ms.CopyTo(f); } } } //if (m_Bitmap == null) //{ // m_Bitmap = new Bitmap(@"D:\Dev\comDemo\Filters\logo.bmp"); // Rectangle bounds = new Rectangle(0, 0, m_Bitmap.Width, m_Bitmap.Height); // var m_BitmapData = m_Bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); // var RowSizeBytes = m_BitmapData.Stride; // int total_size = m_BitmapData.Stride * m_BitmapData.Height; // if (ImageBytes == null || ImageBytes.Length != total_size) // { // ImageBytes = new byte[total_size]; // } // // Copy the data into the ImageBytes array. // Marshal.Copy(m_BitmapData.Scan0, ImageBytes, 0, total_size); // encoder.EncodeRGBtoI420(ImageBytes, m_Bitmap.Width, m_Bitmap.Height, ref yuv, true); //} //else //if(f != null) { //f.OnFillBuffer(pData, lDataLen); } }
unsafe internal static void UpdateNativeProperty( DomNode node, AttributeInfo attribInfo, IList <PropertyInitializer> properties, System.IO.UnmanagedMemoryStream stream) { object idObj = attribInfo.GetTag(NativeAnnotations.NativeProperty); if (idObj == null) { return; } uint id = (uint)idObj; PushAttribute( id, attribInfo.Type.ClrType, attribInfo.Type.Length, node.GetAttribute(attribInfo), properties, stream); }
unsafe private static void SetStringProperty( uint propId, string str, IList <PropertyInitializer> properties, System.IO.UnmanagedMemoryStream stream) { var length = str.Length; properties.Add(GameEngine.CreateInitializer( propId, stream.PositionPointer, typeof(char), (uint)length, true)); // copy in string data with no string formatting or changes to encoding fixed(char *raw = str) for (uint c = 0; c < length; ++c) { ((char *)stream.PositionPointer)[c] = raw[c]; } // just advance the stream position over what we've just written stream.Position += sizeof(char) * length; }
internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) { _unmanagedStream = stream; }
unsafe internal static void PushAttribute( uint propertyId, Type clrType, int arrayLength, object data, IList <PropertyInitializer> properties, System.IO.UnmanagedMemoryStream stream) { Type elmentType = clrType.GetElementType(); if (clrType.IsArray && elmentType.IsPrimitive) { if (elmentType == typeof(float)) { var count = Math.Min(arrayLength, ((float[])data).Length); properties.Add(GameEngine.CreateInitializer( propertyId, stream.PositionPointer, elmentType, (uint)count, false)); fixed(float *d = (float[])data) for (uint c = 0; c < count; ++c) { ((float *)stream.PositionPointer)[c] = d[c]; } stream.Position += sizeof(float) * count; } else if (elmentType == typeof(int)) { var count = Math.Min(arrayLength, ((int[])data).Length); properties.Add(GameEngine.CreateInitializer( propertyId, stream.PositionPointer, elmentType, (uint)count, false)); fixed(int *d = (int[])data) for (uint c = 0; c < count; ++c) { ((int *)stream.PositionPointer)[c] = d[c]; } stream.Position += sizeof(int) * count; } else if (elmentType == typeof(uint)) { var count = Math.Min(arrayLength, ((uint[])data).Length); properties.Add(GameEngine.CreateInitializer( propertyId, stream.PositionPointer, elmentType, (uint)count, false)); fixed(uint *d = (uint[])data) for (uint c = 0; c < count; ++c) { ((uint *)stream.PositionPointer)[c] = d[c]; } stream.Position += sizeof(int) * count; } else { System.Diagnostics.Debug.Assert(false); } } else { if (clrType == typeof(string)) { SetStringProperty(propertyId, (string)data, properties, stream); } else if (clrType == typeof(bool)) { uint d = Convert.ToUInt32((bool)data); SetBasicProperty(propertyId, d, properties, stream); *(uint *)stream.PositionPointer = d; stream.Position += sizeof(uint); } else if (clrType == typeof(byte)) { SetBasicProperty(propertyId, (byte)data, properties, stream); *(byte *)stream.PositionPointer = (byte)data; stream.Position += sizeof(byte); } else if (clrType == typeof(sbyte)) { SetBasicProperty(propertyId, (sbyte)data, properties, stream); *(sbyte *)stream.PositionPointer = (sbyte)data; stream.Position += sizeof(sbyte); } else if (clrType == typeof(short)) { SetBasicProperty(propertyId, (short)data, properties, stream); *(short *)stream.PositionPointer = (short)data; stream.Position += sizeof(short); } else if (clrType == typeof(ushort)) { SetBasicProperty(propertyId, (ushort)data, properties, stream); *(ushort *)stream.PositionPointer = (ushort)data; stream.Position += sizeof(ushort); } else if (clrType == typeof(int)) { SetBasicProperty(propertyId, (int)data, properties, stream); *(int *)stream.PositionPointer = (int)data; stream.Position += sizeof(int); } else if (clrType == typeof(uint)) { SetBasicProperty(propertyId, (uint)data, properties, stream); *(uint *)stream.PositionPointer = (uint)data; stream.Position += sizeof(uint); } else if (clrType == typeof(long)) { SetBasicProperty(propertyId, (long)data, properties, stream); *(long *)stream.PositionPointer = (long)data; stream.Position += sizeof(long); } else if (clrType == typeof(ulong)) { SetBasicProperty(propertyId, (ulong)data, properties, stream); *(ulong *)stream.PositionPointer = (ulong)data; stream.Position += sizeof(ulong); } else if (clrType == typeof(float)) { SetBasicProperty(propertyId, (float)data, properties, stream); *(float *)stream.PositionPointer = (float)data; stream.Position += sizeof(float); } else if (clrType == typeof(double)) { SetBasicProperty(propertyId, (double)data, properties, stream); *(double *)stream.PositionPointer = (double)data; stream.Position += sizeof(double); } else if (clrType == typeof(System.Uri)) { if (data != null) { string assetName = AsAssetName((Uri)data); if (!string.IsNullOrWhiteSpace(assetName)) { SetStringProperty(propertyId, assetName, properties, stream); } } } else if (clrType == typeof(DomNode)) { // this is a 'reference' to an object DomNode refNode = (DomNode)data; NativeObjectAdapter nativeGob = refNode.As <NativeObjectAdapter>(); if (nativeGob != null) { SetBasicProperty(propertyId, (ulong)nativeGob.InstanceId, properties, stream); *(ulong *)stream.PositionPointer = (ulong)nativeGob.InstanceId; stream.Position += sizeof(ulong); } } } }
/// <summary> /// Serializes objectToSerialize to a byte array using compression provided by compressor if T is an array of primitives. Otherwise returns default value for T. Override /// to serialize other types /// </summary> /// <param name="objectToSerialise">Object to serialize</param> /// <param name="dataProcessors">The compression provider to use</param> /// <param name="options">Options to be used during serialization and processing of data</param> /// <returns>The serialized and compressed bytes of objectToSerialize</returns> public static unsafe StreamSendWrapper SerialiseArrayObject(object objectToSerialise, List <DataProcessor> dataProcessors, Dictionary <string, string> options) { Type objType = objectToSerialise.GetType(); if (objType.IsArray) { var elementType = objType.GetElementType(); //No need to do anything for a byte array if (elementType == typeof(byte) && (dataProcessors == null || dataProcessors.Count == 0)) { byte[] bytesToSerialise = objectToSerialise as byte[]; //return objectToSerialise as byte[]; return(new StreamSendWrapper(new ThreadSafeStream(new MemoryStream(bytesToSerialise, 0, bytesToSerialise.Length, false, true), true))); } else if (elementType.IsPrimitive) { var asArray = objectToSerialise as Array; GCHandle arrayHandle = GCHandle.Alloc(asArray, GCHandleType.Pinned); try { IntPtr safePtr = Marshal.UnsafeAddrOfPinnedArrayElement(asArray, 0); long writtenBytes = 0; MemoryStream tempStream1 = new System.IO.MemoryStream(); using (UnmanagedMemoryStream inputDataStream = new System.IO.UnmanagedMemoryStream((byte *)safePtr, asArray.Length * Marshal.SizeOf(elementType))) { if (dataProcessors == null || dataProcessors.Count == 0) { AsyncStreamCopier.CopyStreamTo(inputDataStream, tempStream1); //return tempStream1.ToArray(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true))); } dataProcessors[0].ForwardProcessDataStream(inputDataStream, tempStream1, options, out writtenBytes); } if (dataProcessors.Count > 1) { MemoryStream tempStream2 = new MemoryStream(); for (int i = 1; i < dataProcessors.Count; i += 2) { tempStream1.Seek(0, 0); tempStream1.SetLength(writtenBytes); tempStream2.Seek(0, 0); dataProcessors[i].ForwardProcessDataStream(tempStream1, tempStream2, options, out writtenBytes); if (i + 1 < dataProcessors.Count) { tempStream1.Seek(0, 0); tempStream2.Seek(0, 0); tempStream2.SetLength(writtenBytes); dataProcessors[i].ForwardProcessDataStream(tempStream2, tempStream1, options, out writtenBytes); } } if (dataProcessors.Count % 2 == 0) { tempStream2.SetLength(writtenBytes + 4); tempStream2.Seek(writtenBytes, 0); tempStream2.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int)); //return tempStream2.ToArray(); tempStream1.Dispose(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream2, true))); } else { tempStream1.SetLength(writtenBytes + 4); tempStream1.Seek(writtenBytes, 0); tempStream1.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int)); //return tempStream1.ToArray(); tempStream2.Dispose(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true))); } } else { tempStream1.SetLength(writtenBytes + 4); tempStream1.Seek(writtenBytes, 0); tempStream1.Write(BitConverter.GetBytes(asArray.Length), 0, sizeof(int)); //return tempStream1.ToArray(); return(new StreamSendWrapper(new ThreadSafeStream(tempStream1, true))); } } finally { arrayHandle.Free(); } } } return(null); }
/// <summary> /// Deserializes data object held as compressed bytes in receivedObjectBytes using compressor if desired type is an array of primitives /// </summary> /// <param name="inputStream">Byte array containing serialized and compressed object</param> /// <param name="dataProcessors">Compression provider to use</param> /// <param name="objType">The <see cref="System.Type"/> of the <see cref="object"/> to be returned</param> /// <param name="options">Options to be used during deserialization and processing of data</param> /// <returns>The deserialized object if it is an array, otherwise null</returns> public static unsafe object DeserialiseArrayObject(MemoryStream inputStream, Type objType, List <DataProcessor> dataProcessors, Dictionary <string, string> options) { if (objType.IsArray) { var elementType = objType.GetElementType(); //No need to do anything for a byte array if (elementType == typeof(byte) && (dataProcessors == null || dataProcessors.Count == 0)) { try { return((object)inputStream.GetBuffer()); } catch (UnauthorizedAccessException) { return((object)inputStream.ToArray()); } } if (elementType.IsPrimitive) { int numElements; if (dataProcessors == null || dataProcessors.Count == 0) { numElements = (int)(inputStream.Length / Marshal.SizeOf(elementType)); } else { byte[] temp = new byte[sizeof(int)]; inputStream.Seek(inputStream.Length - sizeof(int), SeekOrigin.Begin); inputStream.Read(temp, 0, sizeof(int)); numElements = (int)(BitConverter.ToUInt32(temp, 0)); } Array resultArray = Array.CreateInstance(elementType, numElements); GCHandle arrayHandle = GCHandle.Alloc(resultArray, GCHandleType.Pinned); try { IntPtr safePtr = Marshal.UnsafeAddrOfPinnedArrayElement(resultArray, 0); long writtenBytes = 0; using (System.IO.UnmanagedMemoryStream finalOutputStream = new System.IO.UnmanagedMemoryStream((byte *)safePtr, resultArray.Length * Marshal.SizeOf(elementType), resultArray.Length * Marshal.SizeOf(elementType), System.IO.FileAccess.ReadWrite)) { MemoryStream inputBytesStream = null; try { //We hope that the buffer is publicly accessible as otherwise it defeats the point of having a special serializer for arrays inputBytesStream = new MemoryStream(inputStream.GetBuffer(), 0, (int)(inputStream.Length - ((dataProcessors == null || dataProcessors.Count == 0) ? 0 : sizeof(int)))); } catch (UnauthorizedAccessException) { inputBytesStream = new MemoryStream(inputStream.ToArray(), 0, (int)(inputStream.Length - ((dataProcessors == null || dataProcessors.Count == 0) ? 0 : sizeof(int)))); } using (inputBytesStream) { if (dataProcessors != null && dataProcessors.Count > 1) { using (MemoryStream tempStream1 = new MemoryStream()) { dataProcessors[dataProcessors.Count - 1].ReverseProcessDataStream(inputBytesStream, tempStream1, options, out writtenBytes); if (dataProcessors.Count > 2) { using (MemoryStream tempStream2 = new MemoryStream()) { for (int i = dataProcessors.Count - 2; i > 0; i -= 2) { tempStream1.Seek(0, 0); tempStream1.SetLength(writtenBytes); tempStream2.Seek(0, 0); dataProcessors[i].ReverseProcessDataStream(tempStream1, tempStream2, options, out writtenBytes); if (i - 1 > 0) { tempStream1.Seek(0, 0); tempStream2.Seek(0, 0); tempStream2.SetLength(writtenBytes); dataProcessors[i - 1].ReverseProcessDataStream(tempStream2, tempStream1, options, out writtenBytes); } } if (dataProcessors.Count % 2 == 0) { tempStream1.Seek(0, 0); tempStream1.SetLength(writtenBytes); dataProcessors[0].ReverseProcessDataStream(tempStream1, finalOutputStream, options, out writtenBytes); } else { tempStream2.Seek(0, 0); tempStream2.SetLength(writtenBytes); dataProcessors[0].ReverseProcessDataStream(tempStream2, finalOutputStream, options, out writtenBytes); } } } else { tempStream1.Seek(0, 0); tempStream1.SetLength(writtenBytes); dataProcessors[0].ReverseProcessDataStream(tempStream1, finalOutputStream, options, out writtenBytes); } } } else { if (dataProcessors != null && dataProcessors.Count == 1) { dataProcessors[0].ReverseProcessDataStream(inputBytesStream, finalOutputStream, options, out writtenBytes); } else { AsyncStreamCopier.CopyStreamTo(inputBytesStream, finalOutputStream); } } } } } finally { arrayHandle.Free(); } return((object)resultArray); } } return(null); }
private void Data_LineReceived(string line) { if (line.Length > 0) { string[] data = line.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (data.Length == 2) { string[] rdata = data[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (rdata.Length == 2) { // Удаляем старые данные while (DATA.radiation.FindAll(item => item.accuracy >= Properties.Settings.Default.min_accuracy).Count() > Properties.Settings.Default.max_data) { DATA.radiation.RemoveAt(0); } // Добавляем новые данные var rd = new radiationData(); rd.time = DateTime.Now; rd.accuracy = Int32.Parse(Regex.Match(data[1].Trim(), @"\d+").Value); rd.value = float.Parse(Regex.Match(rdata[0].Trim(), @"[\d.]+").Value, CultureInfo.InvariantCulture); DATA.radiation.Add(rd); DATA.unit = rdata[1].Trim(); // Обновляем отображаемую информацию RadiationLabel.Text = DATA.radiation.Last().value.ToString() + " " + DATA.unit; AccuracyLabel.Text = String.Format(Translate.GetString("accuracy", Culture), DATA.radiation.Last().accuracy.ToString() + "%"); List <radiationData> all_items = DATA.radiation.FindAll(item => item.accuracy >= Properties.Settings.Default.min_accuracy); if (all_items.Count() > 0) { radiationData last_item = DATA.radiation.FindLast(item => item.accuracy >= Properties.Settings.Default.min_accuracy); // Интерфейс RadiationChart.ChartAreas.FindByName("RadiationChartArea").AxisY.Title = DATA.unit; notifyIcon.Text = Application.ProductName + " [" + last_item.value.ToString() + " " + DATA.unit + "]"; // График if (all_items.Count() > 1) { RadiationChart.Annotations.FindByName("NoDataAnnotation").Visible = false; RadiationChart.Series.FindByName("RadiationSeries").Points.Clear(); foreach (var item in all_items) { RadiationChart.Series.FindByName("RadiationSeries").Points.AddXY(item.time, item.value); } } // Уровни радиации и оповещения if (last_item.value < Properties.Settings.Default.warning_level) // Нормальный уровень { RadiationLabel.ForeColor = System.Drawing.Color.Green; if (LastNotify != 1) { if (Properties.Settings.Default.voice_notify) // Голосовые уведомления { System.IO.UnmanagedMemoryStream player_file = Properties.Resources.ResourceManager.GetStream("normal_" + Culture.TwoLetterISOLanguageName); player_file = (player_file == null ? Properties.Resources.normal_en : player_file); System.Media.SoundPlayer sound_player = new System.Media.SoundPlayer(player_file); sound_player.Play(); } if (notifyIcon.Visible && Properties.Settings.Default.tray_notify) // Уведомления в системном трее { notifyIcon.ShowBalloonTip(5000, Translate.GetString("tray_normal", Culture), String.Format(Translate.GetString("current_value", Culture), RadiationLabel.Text), ToolTipIcon.Info); } LastNotify = 1; } } else if (last_item.value >= Properties.Settings.Default.warning_level && last_item.value < Properties.Settings.Default.danger_level) // Повышенный уровень { RadiationLabel.ForeColor = System.Drawing.Color.Orange; if (LastNotify != 2) { if (Properties.Settings.Default.voice_notify) // Голосовые уведомления { System.IO.UnmanagedMemoryStream player_file = Properties.Resources.ResourceManager.GetStream("warning_" + Culture.TwoLetterISOLanguageName); player_file = (player_file == null ? Properties.Resources.warning_en : player_file); System.Media.SoundPlayer sound_player = new System.Media.SoundPlayer(player_file); sound_player.Play(); } if (notifyIcon.Visible && Properties.Settings.Default.tray_notify) // Уведомления в системном трее { notifyIcon.ShowBalloonTip(5000, Translate.GetString("tray_warning", Culture), String.Format(Translate.GetString("current_value", Culture), RadiationLabel.Text), ToolTipIcon.Warning); } LastNotify = 2; } } else // Опасный уровень { RadiationLabel.ForeColor = System.Drawing.Color.Red; if (LastNotify != 3) { if (Properties.Settings.Default.voice_notify) // Голосовые уведомления { System.IO.UnmanagedMemoryStream player_file = Properties.Resources.ResourceManager.GetStream("danger_" + Culture.TwoLetterISOLanguageName); player_file = (player_file == null ? Properties.Resources.danger_en : player_file); System.Media.SoundPlayer sound_player = new System.Media.SoundPlayer(player_file); sound_player.Play(); } if (notifyIcon.Visible && Properties.Settings.Default.tray_notify) // Уведомления в системном трее { notifyIcon.ShowBalloonTip(5000, Translate.GetString("tray_danger", Culture), String.Format(Translate.GetString("current_value", Culture), RadiationLabel.Text), ToolTipIcon.Error); } LastNotify = 3; } } } } } } }
public static WAVFile Load(System.IO.UnmanagedMemoryStream stream) { return(Load("", stream as Stream)); }