public RawBitmap(Bitmap originBitmap) { OriginBitmap = originBitmap; _bitmapData = OriginBitmap.LockBits(new Rectangle(0, 0, OriginBitmap.Width, OriginBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); _begin = (byte*) (void*) _bitmapData.Scan0; }
unsafe public void create(uint width, uint height, uint BitsPerPixel, uint clear_val) { destroy(); if(width == 0) width = 1; if(height == 0) height = 1; m_BitsPerPixel = BitsPerPixel; switch (m_BitsPerPixel) { case 24: m_bmp = new Bitmap((int)width, (int)height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); break; case 32: m_bmp = new Bitmap((int)width, (int)height, System.Drawing.Imaging.PixelFormat.Format32bppRgb); break; default: throw new System.NotImplementedException(); } m_bmd = m_bmp.LockBits(new Rectangle(0, 0, m_bmp.Width, m_bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, m_bmp.PixelFormat); m_buf = (byte*)m_bmd.Scan0; if (clear_val <= 255) { clear(clear_val); } }
public void Dispose() { handle.Free(); fixedPtr = null; data = null; }
private void Initialize() { Console.WriteLine("Start Ext2.Initialize"); mBuffer = new byte[mBackend.BlockSize]; fixed (byte* xBufferAddress = &mBuffer[0]) { mBufferAddress = xBufferAddress; } // first get the superblock; var mBufferAsSuperblock = (SuperBlock*)mBufferAddress; int xAddr = (int)mBufferAddress; Console.WriteLine("Buffer address: " + xAddr); Console.WriteLine("Start reading superblock"); mBackend.ReadBlock(2, mBuffer); Console.WriteLine("End reading"); mSuperblock = *mBufferAsSuperblock; DebugUtil.Send_Ext2SuperBlock(mSuperblock); // read the group descriptors Console.WriteLine("INodeCount: " + mSuperblock.INodesCount); Console.WriteLine("INode#1: " + mBufferAddress[0]); Console.WriteLine("INode#2: " + mBufferAddress[1]); Console.WriteLine("INode#3: " + mBufferAddress[2]); Console.WriteLine("INode#4: " + mBufferAddress[3]); Console.WriteLine("BlockCount: " + mSuperblock.BlockCount); Console.WriteLine("INodesPerGroup: " + (int)mSuperblock.INodesPerGroup); if (mSuperblock.INodesPerGroup == 0x4000) { Console.WriteLine("INodesPerGroup has correct value!"); } uint xGroupDescriptorCount = mSuperblock.INodesCount / mSuperblock.INodesPerGroup; mGroupDescriptors = new GroupDescriptor[xGroupDescriptorCount]; var xDescriptorPtr = (GroupDescriptor*)mBufferAddress; Console.WriteLine("Process GroupDescriptors: " + xGroupDescriptorCount); //Console.ReadLine(); for (int i = 0; i < xGroupDescriptorCount; i++) { Console.WriteLine("Processing GroupDescriptor " + i); uint xATABlock ; if ( BlockSize == 1024 ) { xATABlock = ( BlockSize * 2 ) / mBackend.BlockSize ; } else { xATABlock = ( BlockSize ) / mBackend.BlockSize ; } xATABlock += (uint)(i / 16); if ((i % 16) == 0) { Console.WriteLine("Read new GroupDescriptorBlock"); mBackend.ReadBlock(xATABlock, mBuffer); Console.WriteLine("End Read"); } mGroupDescriptors[i] = xDescriptorPtr[i % 16]; Console.WriteLine("End of GroupDescriptor check"); } Console.WriteLine("Send GroupDescriptors to log"); DebugUtil.Send_Ext2GroupDescriptors(mGroupDescriptors); }
public double ReadDouble() { double ret = *(double*) fixedPtr; fixedPtr = fixedPtr + 8; position = position + 8; return ret; }
public byte ReadByte() { byte ret = *fixedPtr; position++; fixedPtr = fixedPtr + 1; return ret; }
/// <summary> /// Inits internal pointer and move it to MIN(current position,<paramref name="length"/>) /// </summary> /// <param name="buffer"></param> /// <param name="length"></param> internal void Init(IntPtr buffer, int length) { _buffer = buffer; _length = length; _position =(uint) Math.Min( _position, _length ); _currentPointer = ((byte*)_buffer.ToPointer()) + _position; }
static public void Init(byte* aStartPtr, Native aSize) { if ((Native)aStartPtr % PageSize != 0 && !Debug) { throw new Exception("RAM start must be page aligned."); } else if (aSize % PageSize != 0) { throw new Exception("RAM size must be page aligned."); } mRamStart = aStartPtr; mRamSize = aSize; mPageCount = aSize / PageSize; // We need one status byte for each block. // Intel blocks are 4k (10 bits). So for 4GB, this means // 32 - 12 = 20 bits, 1 MB for a RAT for 4GB. 0.025% Native xRatPageCount = (mPageCount - 1) / PageSize + 1; Native xRatPageBytes = xRatPageCount * PageSize; mRAT = mRamStart + mRamSize - xRatPageBytes; for (byte* p = mRAT; p < mRAT + xRatPageBytes - xRatPageCount; p++) { *p = PageType.Empty; } for (byte* p = mRAT + xRatPageBytes - xRatPageCount; p < mRAT + xRatPageBytes; p++) { *p = PageType.RAT; } Heap.Init(); }
internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) { _enc = inEncoding; _encoder = inEncoder; _charStart = inCharStart; _chars = inCharStart; _charEnd = inCharStart + inCharCount; _bytes = inByteStart; _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; if (_encoder == null) fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); else { fallbackBuffer = _encoder.FallbackBuffer; // If we're not converting we must not have data in our fallback buffer if (_encoder.m_throwOnOverflow && _encoder.InternalHasFallbackBuffer && fallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); } fallbackBufferHelper = new EncoderFallbackBufferHelper(fallbackBuffer); fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); }
public Image(string filename) { // create and bind a new image Il.ilGenImages(1, out imageID); Il.ilBindImage(imageID); // load the data into DevIL Il.ilLoadImage(filename); // check for an error int ilError = Il.ilGetError(); if (ilError != Il.IL_NO_ERROR) { throw new Exception(string.Format("Error while decoding image data: '{0}'", Ilu.iluErrorString(ilError))); } format = Il.ilGetInteger(Il.IL_IMAGE_FORMAT); bytesPerPixel = Math.Max(Il.ilGetInteger(Il.IL_IMAGE_BPC), Il.ilGetInteger(Il.IL_IMAGE_BYTES_PER_PIXEL)); width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH); height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT); depth = Il.ilGetInteger(Il.IL_IMAGE_DEPTH); stride = bytesPerPixel * width; // get the decoded data IntPtr ptr = Il.ilGetData(); // copy the data into the byte array pBuffer = (byte*)ptr; }
internal BlobReader(MemoryBlock block) { Debug.Assert(BitConverter.IsLittleEndian && block.Length >= 0 && (block.Pointer != null || block.Length == 0)); _block = block; _currentPointer = block.Pointer; _endPointer = block.Pointer + block.Length; }
public NativeBufferPool(int bufferSizeInBytes, int numberOfBuffers) { _bufferSizeInBytes = bufferSizeInBytes; _freeList = new int[numberOfBuffers]; _totalBytes = bufferSizeInBytes * numberOfBuffers; _memory = (byte*)Marshal.AllocHGlobal(_totalBytes).ToPointer(); }
public void Set(byte* p, long pageNumber) { Base = p; Header = *((PrefixNodeHeader*)p); ValuePtr = p + Constants.PrefixNodeHeaderSize; PageNumber = pageNumber; }
public unsafe void CancelSyncOperation(ref object holder) { this.bufferPtr = null; holder = dummyBuffer; this.syncOperationPending = false; this.rootedHolder.EventHolder = null; }
public Slice(SliceOptions options) { Options = options; _pointer = null; _array = null; _size = 0; }
/// <summary> /// Read a number of bytes from a stream into unmanaged main memory, and construct /// a container object around it. /// </summary> /// <param name="stream">The stream to read from</param> /// <param name="numBytes">The number of bytes to read</param> public CachedStream(Stream stream, ulong numBytes) { this.size = numBytes; // Allocate unmanaged byte array unsafe { /* This recipe is taken from chapter 18.9 of "The C# Programming Language" (3rd edition) by Hejlsberg et al. According to Yuan Yu, an alternative and possibly better way would be to use System.Runtime.InteropServices.AllocHGlobal. */ this.ph = GetProcessHeap(); this.bytes = (byte*)HeapAlloc(ph, 0, (UIntPtr)this.size); if (this.bytes == null) throw new OutOfMemoryException(); } const int chunkSize = 8192; byte[] buf = new byte[chunkSize]; ulong pos = 0; ulong rem = numBytes; while (rem > 0) { int max = rem < chunkSize ? (int)rem : chunkSize; int n = stream.Read(buf, 0, max); if (n == 0) throw new FileFormatException(string.Format("Stream too short, expected {0} extra bytes", rem)); rem -= (ulong)n; for (int i = 0; i < n; i++) { this.bytes[pos++] = buf[i]; } } if (pos != size) throw new Exception(); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="model">The model the successors are computed for.</param> /// <param name="capacity">The maximum number of successors that can be cached.</param> /// <param name="formulas">The formulas that should be checked for all successor states.</param> public ActivationMinimalTransitionSetBuilder(RuntimeModel model, long capacity, params Func<bool>[] formulas) { Requires.NotNull(model, nameof(model)); Requires.NotNull(formulas, nameof(formulas)); Requires.That(formulas.Length < 32, "At most 32 formulas are supported."); Requires.That(capacity <= (1 << 30), nameof(capacity), $"Maximum supported capacity is {1 << 30}."); _stateVectorSize = model.StateVectorSize; _formulas = formulas; _transitionBuffer.Resize(capacity * sizeof(CandidateTransition), zeroMemory: false); _transitions = (CandidateTransition*)_transitionBuffer.Pointer; _targetStateBuffer.Resize(capacity * model.StateVectorSize, zeroMemory: true); _targetStateMemory = _targetStateBuffer.Pointer; _lookupBuffer.Resize(capacity * sizeof(int), zeroMemory: false); _faultsBuffer.Resize(capacity * sizeof(FaultSetInfo), zeroMemory: false); _hashedStateBuffer.Resize(capacity * _stateVectorSize, zeroMemory: false); _successors = new List<uint>(); _capacity = capacity; _lookup = (int*)_lookupBuffer.Pointer; _faults = (FaultSetInfo*)_faultsBuffer.Pointer; _hashedStateMemory = _hashedStateBuffer.Pointer; for (var i = 0; i < capacity; ++i) _lookup[i] = -1; }
internal unsafe GB18030Encoding() : base(0xd698, 0x3a8) { this.map4BytesToUnicode = null; this.mapUnicodeTo4BytesFlags = null; this.tableUnicodeToGBDiffs = new ushort[] { 0x8080, 0x24, 0x8001, 2, 0x8002, 7, 0x8002, 5, 0x8001, 0x1f, 0x8001, 8, 0x8002, 6, 0x8003, 1, 0x8002, 4, 0x8002, 3, 0x8001, 1, 0x8002, 1, 0x8001, 4, 0x8001, 0x11, 0x8001, 7, 0x8001, 15, 0x8001, 0x18, 0x8001, 3, 0x8001, 4, 0x8001, 0x1d, 0x8001, 0x62, 0x8001, 1, 0x8001, 1, 0x8001, 1, 0x8001, 1, 0x8001, 1, 0x8001, 1, 0x8001, 1, 0x8001, 0x1c, 0xa8bf, 0x57, 0x8001, 15, 0x8001, 0x65, 0x8001, 1, 0x8003, 13, 0x8001, 0xb7, 0x8011, 1, 0x8007, 7, 0x8011, 1, 0x8007, 0x37, 0x8001, 14, 0x8040, 1, 0x8001, 0x1bbe, 0x8001, 2, 0x8004, 1, 0x8002, 2, 0x8002, 7, 0x8002, 9, 0x8001, 1, 0x8002, 1, 0x8001, 5, 0x8001, 0x70, 0xa2e3, 0x56, 0x8001, 1, 0x8001, 3, 0x8001, 12, 0x8001, 10, 0x8001, 0x3e, 0x800c, 4, 0x800a, 0x16, 0x8004, 2, 0x8004, 110, 0x8001, 6, 0x8001, 1, 0x8001, 3, 0x8001, 4, 0x8001, 2, 0x8004, 2, 0x8001, 1, 0x8001, 1, 0x8005, 2, 0x8001, 5, 0x8004, 5, 0x8001, 10, 0x8001, 3, 0x8001, 5, 0x8001, 13, 0x8002, 2, 0x8004, 6, 0x8002, 0x25, 0x8001, 3, 0x8001, 11, 0x8001, 0x19, 0x8001, 0x52, 0x8001, 0x14d, 0x800a, 10, 0x8028, 100, 0x804c, 4, 0x8024, 13, 0x800f, 3, 0x8003, 10, 0x8002, 0x10, 0x8002, 8, 0x8002, 8, 0x8002, 3, 0x8001, 2, 0x8002, 0x12, 0x8004, 0x1f, 0x8002, 2, 0x8001, 0x36, 0x8001, 1, 0x8001, 0x83e, 0xfe50, 2, 0xfe54, 3, 0xfe57, 2, 0xfe58, 0xfe5d, 10, 0xfe5e, 15, 0xfe6b, 2, 0xfe6e, 3, 0xfe71, 4, 0xfe73, 2, 0xfe74, 0xfe75, 3, 0xfe79, 14, 0xfe84, 0x125, 0xa98a, 0xa98b, 0xa98c, 0xa98d, 0xa98e, 0xa98f, 0xa990, 0xa991, 0xa992, 0xa993, 0xa994, 0xa995, 4, 0x8004, 1, 0x8013, 5, 0x8002, 2, 0x8009, 20, 0xa989, 2, 0x8053, 7, 0x8004, 2, 0x8056, 5, 0x8003, 6, 0x8025, 0xf6, 0x800a, 7, 0x8001, 0x71, 0x8001, 0xea, 0x8002, 12, 0x8003, 2, 0x8001, 0x22, 0x8001, 9, 0x8001, 2, 0x8002, 2, 0x8001, 0x71, 0xfe56, 0x2b, 0xfe55, 0x12a, 0xfe5a, 0x6f, 0xfe5c, 11, 0xfe5b, 0x2fd, 0xfe60, 0x55, 0xfe5f, 0x60, 0xfe62, 0xfe65, 14, 0xfe63, 0x93, 0xfe64, 0xda, 0xfe68, 0x11f, 0xfe69, 0x71, 0xfe6a, 0x375, 0xfe6f, 0x108, 0xfe70, 0x1d7, 0xfe72, 0x74, 0xfe78, 4, 0xfe77, 0x2b, 0xfe7a, 0xf8, 0xfe7b, 0x175, 0xfe7d, 20, 0xfe7c, 0xc1, 0xfe80, 5, 0xfe81, 0x52, 0xfe82, 0x10, 0xfe83, 0x1b9, 0xfe85, 50, 0xfe86, 2, 0xfe87, 4, 0xfe88, 0xfe89, 1, 0xfe8a, 0xfe8b, 20, 0xfe8d, 3, 0xfe8c, 0x16, 0xfe8f, 0xfe8e, 0x2bf, 0xfe96, 0x27, 0xfe93, 0xfe94, 0xfe95, 0xfe97, 0xfe92, 0x6f, 0xfe98, 0xfe99, 0xfe9a, 0xfe9b, 0xfe9c, 0xfe9d, 0xfe9e, 0x94, 0xfe9f, 0x51, 0xd1a6, 0x385a, 0x8f6c, 1, 0x805b, 1, 0x801e, 13, 0x8021, 1, 0x8003, 5, 0x8001, 7, 0x8001, 4, 0x8002, 4, 0x8002, 8, 0x8001, 7, 0x8001, 0x10, 0x8002, 14, 0x8001, 0x10c7, 0x8001, 0x4c, 0x8001, 0x1b, 0x8001, 0x51, 0x8001, 9, 0x8001, 0x1a, 0x8004, 1, 0x8001, 1, 0x8002, 3, 0x8001, 6, 0x8003, 1, 0x8002, 2, 0x8003, 0x406, 0x8002, 1, 0x8012, 4, 0x800a, 1, 0x8004, 1, 0x800e, 1, 0x8004, 0x95, 0x805e, 0x81, 0x8006, 0x1a }; }
internal UnmanagedSliceStream(USlice slice) { Contract.Requires(slice.Count == 0 || slice.Data != null); m_begin = slice.Data; m_size = slice.Count; }
public void UnlockImage() { if (mBitmapData != null) { mWorkingBitmap.UnlockBits(mBitmapData); mBitmapData = null; mPointer = null; } }
/// <summary> /// Creates a new CudaRegisteredHostMemory_byte from an existing IntPtr. IntPtr must be page size aligned (4KBytes)! /// </summary> /// <param name="hostPointer">must be page size aligned (4KBytes)</param> /// <param name="size">In elements</param> public CudaRegisteredHostMemory_byte(IntPtr hostPointer, SizeT size) { _intPtr = hostPointer; _size = size; _typeSize = (SizeT)Marshal.SizeOf(typeof(byte)); _ptr = (byte*)_intPtr; }
[System.Security.SecurityCritical] // auto-generated internal unsafe EncodingCharBuffer(EncodingNLS enc, DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount) { _enc = enc; _decoder = decoder; _chars = charStart; _charStart = charStart; _charEnd = charStart + charCount; _byteStart = byteStart; _bytes = byteStart; _byteEnd = byteStart + byteCount; if (_decoder == null) _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); else _fallbackBuffer = _decoder.FallbackBuffer; // If we're getting chars or getting char count we don't expect to have // to remember fallbacks between calls (so it should be empty) Debug.Assert(_fallbackBuffer.Remaining == 0, "[Encoding.EncodingCharBuffer.EncodingCharBuffer]Expected empty fallback buffer for getchars/charcount"); _fallbackBufferHelper = new DecoderFallbackBufferHelper(_fallbackBuffer); _fallbackBufferHelper.InternalInitialize(_bytes, _charEnd); }
internal unsafe SBCSCodePageEncoding(SerializationInfo info, StreamingContext context) : base(0) { this.mapBytesToUnicode = null; this.mapUnicodeToBytes = null; this.mapCodePageCached = null; throw new ArgumentNullException("this"); }
public Filter(Bitmap MainBitmap) { if (MainBitmap != null) { UPicture = (Bitmap)MainBitmap.Clone(); switch (UPicture.PixelFormat) { case PixelFormat.Format32bppRgb: { BytesPerPix = 3; break; } case PixelFormat.Format32bppArgb: { BytesPerPix = 4; break; } default: { throw new NotSupportedException("Формат пикселей не соответствует стандарту"); } } BmpData = UPicture.LockBits(new Rectangle(0, 0, UPicture.Width, UPicture.Height), ImageLockMode.ReadWrite, UPicture.PixelFormat); unsafe { Begin = (byte*)BmpData.Scan0; } } else throw new ArgumentException("Неверный параметр #1"); }
public GridBufferPosition(IPointDataChunk buffer, int index, int count, short entrySize) { m_entrySize = entrySize; DataPtr = buffer.PointDataPtr + (index * m_entrySize); DataEndPtr = DataPtr + (count * m_entrySize); }
public ByteSlice(byte[] buffer, int offset, int count) { _buffer = buffer; _offset = offset; Count = count; _chunk = null; }
public ByteSlice(ByteChunk chunk) { _chunk = chunk.Pointer; _offset = 0; Count = chunk.Length; _buffer = null; }
// Constructor. protected MultiByteEncoding(int codePage, String bodyName, String encodingName, String headerName, String webName, int windowsCodePage, String tableName) : base(codePage) { // Initialize this object's state. this.bodyName = bodyName; this.encodingName = encodingName; this.headerName = headerName; this.webName = webName; this.windowsCodePage = windowsCodePage; this.mainEncoding = (codePage == windowsCodePage); // Load the conversion rules from the resource table. CodeTable table = new CodeTable(tableName); byte *info = table.GetSection(Info_Block); dbyteToUnicode = table.GetSection(DByte_To_Unicode); lowUnicodeToDByte = table.GetSection(Low_Unicode_To_DByte); midUnicodeToDByte = table.GetSection(Mid_Unicode_To_DByte); highUnicodeToDByte = table.GetSection(High_Unicode_To_DByte); table.Dispose(); // Decode the data in the information header block. lowFirst = info[0]; highFirst = info[1]; lowSecond = info[2]; highSecond = info[3]; lowRangeUpper = (info[4] | (info[5] << 8)); midRangeLower = (info[6] | (info[7] << 8)); midRangeUpper = (info[8] | (info[9] << 8)); highRangeLower = (info[10] | (info[11] << 8)); }
[System.Security.SecurityCritical] // auto-generated protected override unsafe void LoadManagedCodePage() { fixed (byte* pBytes = m_codePageHeader) { CodePageHeader* pCodePage = (CodePageHeader*)pBytes; // Should be loading OUR code page Debug.Assert(pCodePage->CodePage == dataTableCodePage, "[SBCSCodePageEncoding.LoadManagedCodePage]Expected to load data table code page"); // Make sure we're really a 1 byte code page if (pCodePage->ByteCount != 1) throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); // Remember our unknown bytes & chars _byteUnknown = (byte)pCodePage->ByteReplace; _charUnknown = pCodePage->UnicodeReplace; // Get our mapped section 65536 bytes for unicode->bytes, 256 * 2 bytes for bytes->unicode // Plus 4 byte to remember CP # when done loading it. (Don't want to get IA64 or anything out of alignment) byte* pNativeMemory = GetNativeMemory(65536 * 1 + 256 * 2 + 4 + iExtraBytes); _mapBytesToUnicode = (char*)pNativeMemory; _mapUnicodeToBytes = (byte*)(pNativeMemory + 256 * 2); // Need to read our data file and fill in our section. // WARNING: Multiple code pieces could do this at once (so we don't have to lock machine-wide) // so be careful here. Only stick legal values in here, don't stick temporary values. // Read our data file and set mapBytesToUnicode and mapUnicodeToBytes appropriately // First table is just all 256 mappings byte[] buffer = new byte[256 * sizeof(char)]; lock (s_streamLock) { s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(buffer, 0, buffer.Length); } fixed (byte* pBuffer = buffer) { char* pTemp = (char*)pBuffer; for (int b = 0; b < 256; b++) { // Don't want to force 0's to map Unicode wrong. 0 byte == 0 unicode already taken care of if (pTemp[b] != 0 || b == 0) { _mapBytesToUnicode[b] = pTemp[b]; if (pTemp[b] != UNKNOWN_CHAR) _mapUnicodeToBytes[pTemp[b]] = (byte)b; } else { _mapBytesToUnicode[b] = UNKNOWN_CHAR; } } } } }
public PlatformMemoryStream(IPlatformMemory mem) { _mem = mem; _data = (byte*)mem.Data; _cap = mem.Capacity; _len = mem.Length; }
public static extern int x16r(byte *input, byte *output, uint inputLength);
private NtStatus ReadEntryWaveData(VirtualWaveBank waveBank, long absOffset, IntPtr handle, IntPtr hEvent, IntPtr *apcRoutine, IntPtr *apcContext, ref Native.IO_STATUS_BLOCK ioStatus, byte *buffer, uint length, Native.LARGE_INTEGER *byteOffset, IntPtr key) { var status = NtStatus.Success; var handled = false; var segBaseOffset = waveBank.Native.Header->Segments[(int)WaveBankSegmentIndex.EntryWaveData].Offset; var segOffset = absOffset - segBaseOffset; for (int i = 0; i < waveBank.Entries.Count; i++) { var entry = waveBank.Entries[i]; if (segOffset < entry.Native->PlayRegion.Offset || segOffset >= (entry.Native->PlayRegion.Offset + entry.Native->PlayRegion.Length)) { continue; } var fileDataOffset = segOffset - entry.Native->PlayRegion.Offset; var readEndOffset = fileDataOffset + length; var nextDataOffset = i < waveBank.Entries.Count - 1 ? waveBank.Entries[i + 1].Native->PlayRegion.Offset : (waveBank.VirtualFileSize - segBaseOffset); if (readEndOffset > nextDataOffset) { continue; } handled = true; if (!entry.IsRedirected) { // Trigger cache miss for (int j = 0; j < mCache.Length; j++) { var cacheEntry = mCache[j].Entry; if (mCache[j].Miss()) { mLogger.Debug($"{waveBank.FileName} Hnd: {handle} Index: {j} {cacheEntry.CueName} removed from cache"); } } mLogger.Info($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} Data access Offset: 0x{absOffset:X8} Length: 0x{length:X8}"); status = mHooks.NtReadFileHook.OriginalFunction(handle, hEvent, apcRoutine, apcContext, ref ioStatus, buffer, length, byteOffset, key); } else { mLogger.Info($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} Data access Offset: 0x{absOffset:X8} Length: 0x{length:X8} redirected to {entry.FilePath}"); status = NtStatus.Success; if (fileDataOffset < 0) { mLogger.Error($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} Offset is before start of data!!!"); continue; } else if (fileDataOffset > entry.FileSize) { mLogger.Error($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} Offset is after end of data!!!"); //continue; } mLogger.Debug($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} Reading 0x{length:X8} bytes from redirected file at offset 0x{fileDataOffset:X8}"); // Get cached file stream if the file was previously opened or open a new file Stream redirectedStream = null; for (int j = 0; j < mCache.Length; j++) { if (mCache[j].Entry == entry) { // Found entry in cache, increase score mCache[j].Hit(); mLogger.Debug($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} loaded from cache"); redirectedStream = mCache[j].Stream; break; } else { // Entry is not the one we're looking for, so we lower its score var cacheEntry = mCache[j].Entry; if (mCache[j].Miss()) { mLogger.Debug($"{waveBank.FileName} Hnd: {handle} Index: {j} {cacheEntry.CueName} removed from cache"); } } } if (redirectedStream == null) { // Wasn't found in cache mLogger.Debug($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} added to cache"); redirectedStream = entry.OpenRead(); for (int j = 0; j < mCache.Length; j++) { if (mCache[j].Entry == null) { mCache[j] = new CacheEntry() { Entry = entry, Score = 1, Stream = redirectedStream }; break;; } } } // Read from redirected file into the buffer try { redirectedStream.Seek(fileDataOffset, SeekOrigin.Begin); var readBytes = redirectedStream.Read(new Span <byte>(( void * )buffer, ( int )length)); SetBytesRead(handle, ( int )waveBank.FilePointer, ( int )length, ref ioStatus); if (readBytes != length) { mLogger.Error($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} File read length doesnt match requested read length!! Expected 0x{length:X8}, Actual 0x{readBytes:X8}"); } mLogger.Debug($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} Wrote redirected file to buffer"); } catch (Exception e) { mLogger.Debug($"{waveBank.FileName} Hnd: {handle} Index: {i} {entry.CueName} Unhandled exception thrown during reading {entry.FileName}: {e}"); } } } if (!handled) { mLogger.Error($"{waveBank.FileName} Hnd: {handle} Unhandled file data read request!! Offset: 0x{absOffset:X8} Length: 0x{length:X8}"); status = mHooks.NtReadFileHook.OriginalFunction(handle, hEvent, apcRoutine, apcContext, ref ioStatus, buffer, length, byteOffset, key); } return(status); }
private static unsafe int AlpnServerSelectCallback(IntPtr ssl, out byte *outp, out byte outlen, byte *inp, uint inlen, IntPtr arg) { outp = null; outlen = 0; GCHandle protocolHandle = GCHandle.FromIntPtr(arg); if (!(protocolHandle.Target is List <SslApplicationProtocol> protocolList)) { return(Ssl.SSL_TLSEXT_ERR_ALERT_FATAL); } try { for (int i = 0; i < protocolList.Count; i++) { var clientList = new Span <byte>(inp, (int)inlen); while (clientList.Length > 0) { byte length = clientList[0]; Span <byte> clientProto = clientList.Slice(1, length); if (clientProto.SequenceEqual(protocolList[i].Protocol.Span)) { fixed(byte *p = &MemoryMarshal.GetReference(clientProto)) outp = p; outlen = length; return(Ssl.SSL_TLSEXT_ERR_OK); } clientList = clientList.Slice(1 + length); } } } catch { // No common application protocol was negotiated, set the target on the alpnHandle to null. // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed. protocolHandle.Target = null; return(Ssl.SSL_TLSEXT_ERR_ALERT_FATAL); } // No common application protocol was negotiated, set the target on the alpnHandle to null. // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed. protocolHandle.Target = null; return(Ssl.SSL_TLSEXT_ERR_ALERT_FATAL); }
public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload) { uint status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { Guid activityId = GetActivityId(); unsafe { int argCount = 0; EventData *userDataPtr = null; if ((eventPayload != null) && (eventPayload.Length != 0)) { argCount = eventPayload.Length; if (argCount > s_etwMaxMumberArguments) { // //too many arguments to log // throw new ArgumentOutOfRangeException("eventPayload", SR.GetString(SR.ArgumentOutOfRange_MaxArgExceeded, s_etwMaxMumberArguments)); } uint totalEventSize = 0; int index; int stringIndex = 0; int[] stringPosition = new int[s_etwAPIMaxStringCount]; //used to keep the position of strings in the eventPayload parameter string[] dataString = new string[s_etwAPIMaxStringCount]; // string arrays from the eventPayload parameter EventData *userData = stackalloc EventData[argCount]; // allocation for the data descriptors userDataPtr = (EventData *)userData; byte *dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // 16 byte for unboxing non-string argument byte *currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Caculates the total size of the event by adding the data descriptor // size value set in EncodeObjec method. // for (index = 0; index < eventPayload.Length; index++) { string isString; isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer); currentBuffer += s_basicTypeAllocationBufferSize; totalEventSize += userDataPtr->Size; userDataPtr++; if (isString != null) { if (stringIndex < s_etwAPIMaxStringCount) { dataString[stringIndex] = isString; stringPosition[stringIndex] = index; stringIndex++; } else { throw new ArgumentOutOfRangeException("eventPayload", SR.GetString(SR.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount)); } } } if (totalEventSize > s_traceEventMaximumSize) { t_returnCode = WriteEventErrorCode.EventTooBig; return(false); } fixed(char *v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3], v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7]) { userDataPtr = (EventData *)userData; if (dataString[0] != null) { userDataPtr[stringPosition[0]].DataPointer = (ulong)v0; } if (dataString[1] != null) { userDataPtr[stringPosition[1]].DataPointer = (ulong)v1; } if (dataString[2] != null) { userDataPtr[stringPosition[2]].DataPointer = (ulong)v2; } if (dataString[3] != null) { userDataPtr[stringPosition[3]].DataPointer = (ulong)v3; } if (dataString[4] != null) { userDataPtr[stringPosition[4]].DataPointer = (ulong)v4; } if (dataString[5] != null) { userDataPtr[stringPosition[5]].DataPointer = (ulong)v5; } if (dataString[6] != null) { userDataPtr[stringPosition[6]].DataPointer = (ulong)v6; } if (dataString[7] != null) { userDataPtr[stringPosition[7]].DataPointer = (ulong)v7; } } } if (relatedActivityId == Guid.Empty && s_preWin7) { // If relatedActivityId is Guid.Empty, this is not a real transfer: just call EventWrite(). // For pre-Win7 platforms we cannot set the activityId from CorrelationManager // because we cannot set relatedActivityId to null (Win7 status = UnsafeNativeMethods.EventWrite(m_regHandle, ref eventDescriptor, (uint)argCount, userDataPtr); } else { status = UnsafeNativeMethods.EventWriteTransfer(m_regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, (relatedActivityId == Guid.Empty && !s_preWin7)? null : &relatedActivityId, (uint)argCount, userDataPtr); } } } if (status != 0) { SetLastError((int)status); return(false); } return(true); }
//basic histograms public static Bitmap[] Histograms(Bitmap b, int brPodX, int brPodY, int nijansaSive) { Bitmap[] arr = new Bitmap[3]; int[] rH = new int[brPodX]; int[] gH = new int[brPodX]; int[] bH = new int[brPodX]; int max = 0; arr[0] = new Bitmap(brPodX, brPodY); arr[1] = new Bitmap(brPodX, brPodY); arr[2] = new Bitmap(brPodX, brPodY); // GDI+ still lies to us - the return format is BGR, NOT RGB. BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); BitmapData bmDataR = arr[0].LockBits(new Rectangle(0, 0, arr[0].Width, arr[0].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); BitmapData bmDataG = arr[1].LockBits(new Rectangle(0, 0, arr[1].Width, arr[1].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); BitmapData bmDataB = arr[2].LockBits(new Rectangle(0, 0, arr[2].Width, arr[2].Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); System.IntPtr Scan0 = bmData.Scan0; System.IntPtr ScanX = bmDataR.Scan0; System.IntPtr ScanY = bmDataG.Scan0; System.IntPtr ScanZ = bmDataB.Scan0; int stride = bmData.Stride; unsafe { byte *p = (byte *)(void *)Scan0; int nOffset = stride - b.Width * 3; int nWidth = b.Width * 3; for (int i = 0; i < b.Height; ++i) { for (int j = 0; j < nWidth; j += 3) { //Odvajanje Red komponete double R = p[2]; R = (R * brPodX) / 256; rH[(int)R]++; max = (rH[(int)R] > max) ? rH[(int)R] : max; //Odvajanje Green komponete double G = p[1]; G = (G * brPodX) / 256; gH[(int)G]++; max = (gH[(int)G] > max) ? gH[(int)G] : max; //Odvajanje Blue komponete double B = p[0]; B = (B * brPodX) / 256; bH[(int)B]++; max = (bH[(int)B] > max) ? bH[(int)B] : max; p += 3; } p += nOffset; } stride = bmDataR.Stride; nOffset = stride - arr[0].Width * 3; nWidth = arr[0].Width * 3; byte *x = (byte *)(void *)ScanX; byte *y = (byte *)(void *)ScanY; byte *z = (byte *)(void *)ScanZ; for (int i = 0; i < brPodY; ++i) { for (int j = 0; j < nWidth; j = j + 3) { x[0] = ((int)(((double)rH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)0 : (byte)nijansaSive; x[1] = ((int)(((double)rH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)0 : (byte)nijansaSive; x[2] = ((int)(((double)rH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)255 : (byte)nijansaSive; x += 3; y[0] = ((int)(((double)gH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)0 : (byte)nijansaSive; y[1] = ((int)(((double)gH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)255 : (byte)nijansaSive; y[2] = ((int)(((double)gH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)0 : (byte)nijansaSive; y += 3; z[0] = ((int)(((double)bH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)255 : (byte)nijansaSive; z[1] = ((int)(((double)bH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)0 : (byte)nijansaSive; z[2] = ((int)(((double)bH[j / 3] / (double)max) * (double)brPodY) >= (brPodY - i)) ? (byte)0 : (byte)nijansaSive; z += 3; } x += nOffset; y += nOffset; z += nOffset; } } b.UnlockBits(bmData); arr[0].UnlockBits(bmDataR); arr[1].UnlockBits(bmDataG); arr[2].UnlockBits(bmDataB); return(arr); }
private static unsafe extern int SocketRead(int fd, byte* buffer, int size);
// // After PInvoke call the method will fix the refHandle.handle with the returned value. // The caller is responsible for creating a correct SafeHandle template or null can be passed if no handle is returned. // // This method switches between three non-interruptible helper methods. (This method can't be both non-interruptible and // reference imports from all three DLLs - doing so would cause all three DLLs to try to be bound to.) // public unsafe static int QueryContextAttributes(SafeDeleteContext phContext, Interop.Secur32.ContextAttribute contextAttribute, byte* buffer, SafeHandle refHandle) { return QueryContextAttributes_SECURITY(phContext, contextAttribute, buffer, refHandle); }
private static unsafe void *Align(byte *buffer, ulong expectedAlignment) { return((void *)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1))); }
public static bool TryFormat(this Guid value, Span <byte> buffer, TextFormat format, EncodingData encoding, out int bytesWritten) { if (format.IsDefault) { format.Symbol = 'G'; } Precondition.Require(format.Symbol == 'G' || format.Symbol == 'D' || format.Symbol == 'N' || format.Symbol == 'B' || format.Symbol == 'P'); bool dash = true; char tail = '\0'; bytesWritten = 0; switch (format.Symbol) { case 'D': case 'G': break; case 'N': dash = false; break; case 'B': if (!TryWriteChar('{', buffer, encoding.TextEncoding, ref bytesWritten)) { return(false); } tail = '}'; break; case 'P': if (!TryWriteChar('(', buffer, encoding.TextEncoding, ref bytesWritten)) { return(false); } tail = ')'; break; default: Precondition.Require(false); // how did we get here? break; } var byteFormat = new TextFormat('x', 2); unsafe { byte *bytes = (byte *)&value; if (!TryWriteByte(bytes[3], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[2], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[1], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[0], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (dash) { if (!TryWriteChar('-', buffer, encoding.TextEncoding, ref bytesWritten)) { return(false); } } if (!TryWriteByte(bytes[5], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[4], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (dash) { if (!TryWriteChar('-', buffer, encoding.TextEncoding, ref bytesWritten)) { return(false); } } if (!TryWriteByte(bytes[7], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[6], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (dash) { if (!TryWriteChar('-', buffer, encoding.TextEncoding, ref bytesWritten)) { return(false); } } if (!TryWriteByte(bytes[8], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[9], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (dash) { if (!TryWriteChar('-', buffer, encoding.TextEncoding, ref bytesWritten)) { return(false); } } if (!TryWriteByte(bytes[10], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[11], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[12], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[13], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[14], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } if (!TryWriteByte(bytes[15], buffer, byteFormat, encoding, ref bytesWritten)) { return(false); } } if (tail != '\0') { if (!TryWriteChar(tail, buffer, encoding.TextEncoding, ref bytesWritten)) { return(false); } } return(true); }
public override unsafe int GetCharCount(byte* bytes, int count) { return GetCharCount(new ReadOnlySpan<byte>(bytes, count)); }
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return s_utf8Encoding.GetBytes(chars, charCount, bytes, byteCount); }
public static unsafe void SetIPv4Address(byte[] buffer, byte *address) { uint addr = (uint)System.Runtime.InteropServices.Marshal.ReadInt32((IntPtr)address); SetIPv4Address(buffer, addr); }
public unsafe static void GenerateFrame(IntPtr _ptr, int length, bool mirrored, bool zoom) { byte[] greenScreen = greenScreenFrameData; void * camData = _ptr.ToPointer(); try { InitializeSensor(); if (greenScreen != null) { int colorFramePointerStart = zoom ? ZoomedPointerStart : 0; int colorFramePointerEnd = zoom ? ZoomedPointerEnd - 1 : greenScreen.Length - 1; int width = zoom ? ZoomedWidth : SensorWidth; if (!mirrored) { fixed(byte *sDataB = &greenScreen[colorFramePointerStart]) fixed(byte *sDataE = &greenScreen[colorFramePointerEnd]) { byte *pData = (byte *)camData; byte *sData = (byte *)sDataE; bool redo = true; for (; sData > sDataB;) { for (var i = 0; i < width; ++i) { var p = sData - 3; * pData++ = *p++; * pData++ = *p++; * pData++ = *p++; if (zoom) { p = sData - 3; *pData++ = *p++; *pData++ = *p++; *pData++ = *p++; } sData -= 4; } if (zoom) { if (redo) { sData += width * 4; } else { sData -= (SensorWidth - ZoomedWidth) * 4; } redo = !redo; } } } } else { fixed(byte *sDataB = &greenScreen[colorFramePointerStart]) fixed(byte *sDataE = &greenScreen[colorFramePointerEnd]) { byte *pData = (byte *)camData; byte *sData = (byte *)sDataE; var sDataBE = sData; var p = sData; var r = sData; bool redo = true; while (sData == (sDataBE = sData) && sDataB <= (sData -= (width * 4 - 1))) { r = sData; do { p = sData; *pData++ = *p++; *pData++ = *p++; *pData++ = *p++; if (zoom) { p = sData; *pData++ = *p++; *pData++ = *p++; *pData++ = *p++; } }while ((sData += 4) <= sDataBE); sData = r - 1; if (zoom) { if (redo) { sData += width * 4; } else { sData -= (SensorWidth - ZoomedWidth) * 4; } redo = !redo; } } } } } } catch { Trace.WriteLine("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\error!!"); byte *pData = (byte *)camData; for (int i = 0; i < length; ++i) { *pData++ = 0; } } }
private static void Reader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e) { bitmap = new WriteableBitmap(colorWidth, colorHeight, 96.0, 96.0, PixelFormats.Bgra32, null); // Calculate the WriteableBitmap back buffer size bitmapBackBufferSize = (uint)((bitmap.BackBufferStride * (bitmap.PixelHeight - 1)) + (bitmap.PixelWidth * bytesPerPixel)); int depthWidth = 0; int depthHeight = 0; DepthFrame depthFrame = null; ColorFrame colorFrame = null; BodyIndexFrame bodyIndexFrame = null; bool isBitmapLocked = false; MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame(); // If the Frame has expired by the time we process this event, return. if (multiSourceFrame == null) { return; } // We use a try/finally to ensure that we clean up before we exit the function. // This includes calling Dispose on any Frame objects that we may have and unlocking the bitmap back buffer. try { depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame(); colorFrame = multiSourceFrame.ColorFrameReference.AcquireFrame(); bodyIndexFrame = multiSourceFrame.BodyIndexFrameReference.AcquireFrame(); // If any frame has expired by the time we process this event, return. // The "finally" statement will Dispose any that are not null. if ((depthFrame == null) || (colorFrame == null) || (bodyIndexFrame == null)) { return; } // Process Depth FrameDescription depthFrameDescription = depthFrame.FrameDescription; depthWidth = depthFrameDescription.Width; depthHeight = depthFrameDescription.Height; // Access the depth frame data directly via LockImageBuffer to avoid making a copy using (KinectBuffer depthFrameData = depthFrame.LockImageBuffer()) { coordinateMapper.MapColorFrameToDepthSpaceUsingIntPtr( depthFrameData.UnderlyingBuffer, depthFrameData.Size, colorMappedToDepthPoints); } // We're done with the DepthFrame depthFrame.Dispose(); depthFrame = null; // Process Color Trace.WriteLine("\n\n\n\n BEFORE LOCK \n\n\n\n"); // Lock the bitmap for writing bitmap.Lock(); Trace.WriteLine("\n\n\n\n LOCK!!!! \n\n\n\n"); colorFrame.CopyConvertedFrameDataToIntPtr(bitmap.BackBuffer, bitmapBackBufferSize, ColorImageFormat.Bgra); // We're done with the ColorFrame colorFrame.Dispose(); colorFrame = null; // We'll access the body index data directly to avoid a copy using (KinectBuffer bodyIndexData = bodyIndexFrame.LockImageBuffer()) { unsafe { byte *bodyIndexDataPointer = (byte *)bodyIndexData.UnderlyingBuffer; int colorMappedToDepthPointCount = colorMappedToDepthPoints.Length; fixed(DepthSpacePoint *colorMappedToDepthPointsPointer = colorMappedToDepthPoints) { // Treat the color data as 4-byte pixels uint *bitmapPixelsPointer = (uint *)bitmap.BackBuffer; // Loop over each row and column of the color image // Zero out any pixels that don't correspond to a body index for (int colorIndex = 0; colorIndex < colorMappedToDepthPointCount; ++colorIndex) { float colorMappedToDepthX = colorMappedToDepthPointsPointer[colorIndex].X; float colorMappedToDepthY = colorMappedToDepthPointsPointer[colorIndex].Y; // The sentinel value is -inf, -inf, meaning that no depth pixel corresponds to this color pixel. if (!float.IsNegativeInfinity(colorMappedToDepthX) && !float.IsNegativeInfinity(colorMappedToDepthY)) { // Make sure the depth pixel maps to a valid point in color space int depthX = (int)(colorMappedToDepthX + 0.5f); int depthY = (int)(colorMappedToDepthY + 0.5f); // If the point is not valid, there is no body index there. if ((depthX >= 0) && (depthX < depthWidth) && (depthY >= 0) && (depthY < depthHeight)) { int depthIndex = (depthY * depthWidth) + depthX; // If we are tracking a body for the current pixel, do not zero out the pixel if (bodyIndexDataPointer[depthIndex] != 0xff) { continue; } } } bitmapPixelsPointer[colorIndex] = 0; } } bitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, bitmap.PixelWidth, bitmap.PixelHeight)); } } } finally { if (isBitmapLocked) { bitmap.Unlock(); var w = bitmap.PixelWidth; var h = bitmap.PixelHeight; var stride = w * ((bitmap.Format.BitsPerPixel + 7) / 8); var bitmapData = new byte[h * stride]; bitmap.CopyPixels(bitmapData, stride, 0); //greenScreenFrameData } if (depthFrame != null) { depthFrame.Dispose(); } if (colorFrame != null) { colorFrame.Dispose(); } if (bodyIndexFrame != null) { bodyIndexFrame.Dispose(); } } }
public unsafe partial void SpecializeShader([Flow(FlowDirection.In)] uint shader, [Flow(FlowDirection.In)] byte *pEntryPoint, [Flow(FlowDirection.In)] uint numSpecializationConstants, [Flow(FlowDirection.In)] uint *pConstantIndex, [Flow(FlowDirection.In)] in uint pConstantValue);
private void savePLY() { int rw = _maxMap.W; int rh = _maxMap.H; int count = 0; for (int y = 0; y < rh; ++y) { for (int x = 0; x < rw; ++x) { if (_maxMap[x, y] > 0) { ++count; } } } var xk = _w / rw; var yk = _h / rh; // load last bitmap using (var bmp = new Bitmap(_fileNames[_fileNames.Length - 1])) { BitmapData dstData = bmp.LockBits(new Rectangle(0, 0, _w, _h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int pixelSize = 4; // open ply file using (var sw = new StreamWriter(pickName("shot", "ply"))) { // write ply header sw.WriteLine("ply"); sw.WriteLine("format ascii 1.0"); sw.WriteLine("comment PLY generated with DepthInition by Giancarlo Todone"); sw.WriteLine("element vertex " + count); sw.WriteLine("property float x"); sw.WriteLine("property float y"); sw.WriteLine("property float z"); sw.WriteLine("property uchar red"); sw.WriteLine("property uchar green"); sw.WriteLine("property uchar blue"); sw.WriteLine("end_header"); float invScale = 1.0f / (float)Math.Max(rw, rh); float xOffs = -0.5f * (float)rw * invScale; float yOffs = -0.5f * (float)rh * invScale; float zk = StackInterDistance; float zOffs = StackInterDistance * (float)(_imgfs.Count) * 0.5f; unsafe { // access bitmap data int dstStride = dstData.Stride; for (int y = 0; y < rh; ++y) { int by = y * yk; byte *dstRow = (byte *)dstData.Scan0 + dstStride * by; for (int x = 0; x < rw; ++x) { var v = _maxMap[x, y]; if (v >= 0) { int i = x * xk * pixelSize; byte b = dstRow[i]; byte g = dstRow[i + 1]; byte r = dstRow[i + 2]; float px, py, pz; getPerspectiveCorrected3DPoint(x, y, out px, out py, out pz); // write point sw.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:0.000} {1:0.000} {2:0.000} {3} {4} {5}", px, py, pz, r, g, b)); } } dstRow += dstStride; } } } bmp.UnlockBits(dstData); } }
private static unsafe extern int SetSocketOpt(int fd, int level, int optName, byte* optVal, int optlen);
protected bool Open() { Close(); try { // Attempts to create or open the shared memory with a name of this.Name if (IsOwnerOfSharedMemory) { // Create a new shared memory mapping Mmf = MemoryMappedFile.CreateNew(Name, SharedMemorySize); // Create a view to the entire region of the shared memory View = Mmf.CreateViewAccessor(0, SharedMemorySize, MemoryMappedFileAccess.ReadWrite); View.SafeMemoryMappedViewHandle.AcquirePointer(ref ViewPtr); Header = (SharedHeader*)(ViewPtr + HeaderOffset); BufferStartPtr = ViewPtr + BufferOffset; // Initialise the header InitialiseHeader(); } else { // Open an existing shared memory mapping Mmf = MemoryMappedFile.OpenExisting(Name); // Retrieve the header from the shared memory in order to initialise the correct size using (var headerView = Mmf.CreateViewAccessor(0, HeaderOffset + Marshal.SizeOf(typeof(SharedHeader)), MemoryMappedFileAccess.Read)) { byte* headerPtr = null; headerView.SafeMemoryMappedViewHandle.AcquirePointer(ref headerPtr); var header = (SharedHeader*)(headerPtr + HeaderOffset); BufferSize = header->SharedMemorySize - Marshal.SizeOf(typeof(SharedHeader)); headerView.SafeMemoryMappedViewHandle.ReleasePointer(); } // Create a view to the entire region of the shared memory View = Mmf.CreateViewAccessor(0, SharedMemorySize, MemoryMappedFileAccess.ReadWrite); View.SafeMemoryMappedViewHandle.AcquirePointer(ref ViewPtr); Header = (SharedHeader*)(ViewPtr + HeaderOffset); BufferStartPtr = ViewPtr + HeaderOffset + Marshal.SizeOf(typeof(SharedHeader)); } } catch { Close(); throw; } // Complete any additional open logic try { if (!DoOpen()) { Close(); return false; } else { return true; } } catch { Close(); throw; } }
public unsafe void Execute() { var snapshotAck = ackFromEntity[connectionEntity]; var ackTick = snapshotAck.LastReceivedSnapshotByRemote; DataStreamWriter dataStream = new DataStreamWriter(2048, Allocator.Temp); dataStream.Clear(); dataStream.Write((byte)NetworkStreamProtocol.Snapshot); dataStream.Write(localTime); dataStream.Write(snapshotAck.LastReceivedRemoteTime - (localTime - snapshotAck.LastReceiveTimestamp)); dataStream.Write(currentTick); int entitySize = UnsafeUtility.SizeOf <Entity>(); var despawnLenWriter = dataStream.Write((uint)0); var updateLenWriter = dataStream.Write((uint)0); uint despawnLen = 0; // TODO: if not all despawns fit, sort them based on age and maybe time since last send // TODO: only resend despawn on nack // FIXME: the TargetPacketSize cannot be used since CleanupGhostJob relies on all ghosts being sent every frame for (var chunk = 0; chunk < despawnChunks.Length /*&& dataStream.Length < TargetPacketSize*/; ++chunk) { var entities = despawnChunks[chunk].GetNativeArray(entityType); var ghosts = despawnChunks[chunk].GetNativeArray(ghostSystemStateType); for (var ent = 0; ent < entities.Length /*&& dataStream.Length < TargetPacketSize*/; ++ent) { if (ackTick == 0 || SequenceHelpers.IsNewer(ghosts[ent].despawnTick, ackTick)) { dataStream.WritePackedUInt((uint)ghosts[ent].ghostId, compressionModel); ++despawnLen; } } } uint updateLen = 0; var serialChunks = new NativeList <PrioChunk>(ghostChunks.Length + serialSpawnChunks.Length, Allocator.Temp); serialChunks.AddRange(serialSpawnChunks); var existingChunks = new NativeHashMap <ArchetypeChunk, int>(ghostChunks.Length, Allocator.Temp); int maxCount = 0; for (int chunk = 0; chunk < ghostChunks.Length; ++chunk) { SerializationState chunkState; var addNew = !chunkSerializationData.TryGetValue(ghostChunks[chunk], out chunkState); // FIXME: should be using chunk sequence number instead of this hack if (!addNew && chunkState.arch != ghostChunks[chunk].Archetype) { UnsafeUtility.Free(chunkState.snapshotData, Allocator.Persistent); chunkSerializationData.Remove(ghostChunks[chunk]); addNew = true; } if (addNew) { chunkState.lastUpdate = currentTick - 1; chunkState.startIndex = 0; chunkState.ghostType = serializers.FindSerializer(ghostChunks[chunk].Archetype); chunkState.arch = ghostChunks[chunk].Archetype; chunkState.snapshotWriteIndex = 0; int serializerDataSize = serializers.GetSnapshotSize(chunkState.ghostType); chunkState.snapshotData = (byte *)UnsafeUtility.Malloc(UnsafeUtility.SizeOf <int>() * GhostSystemConstants.SnapshotHistorySize + GhostSystemConstants.SnapshotHistorySize * ghostChunks[chunk].Capacity * (UnsafeUtility.SizeOf <Entity>() + serializerDataSize), 16, Allocator.Persistent); // Just clear snapshot index UnsafeUtility.MemClear(chunkState.snapshotData, UnsafeUtility.SizeOf <int>() * GhostSystemConstants.SnapshotHistorySize); chunkSerializationData.TryAdd(ghostChunks[chunk], chunkState); } existingChunks.TryAdd(ghostChunks[chunk], 1); // FIXME: only if modified or force sync var ghostType = chunkState.ghostType; var pc = new PrioChunk { chunk = ghostChunks[chunk], ghostState = null, priority = serializers.CalculateImportance(ghostType, ghostChunks[chunk]) * (int)(currentTick - chunkState.lastUpdate), startIndex = chunkState.startIndex, ghostType = ghostType }; serialChunks.Add(pc); if (ghostChunks[chunk].Count > maxCount) { maxCount = ghostChunks[chunk].Count; } } var oldChunks = chunkSerializationData.GetKeyArray(Allocator.Temp); for (int i = 0; i < oldChunks.Length; ++i) { int val; if (!existingChunks.TryGetValue(oldChunks[i], out val)) { SerializationState chunkState; chunkSerializationData.TryGetValue(oldChunks[i], out chunkState); UnsafeUtility.Free(chunkState.snapshotData, Allocator.Persistent); chunkSerializationData.Remove(oldChunks[i]); } } NativeArray <PrioChunk> serialChunkArray = serialChunks; serialChunkArray.Sort(); var availableBaselines = new NativeList <SnapshotBaseline>(GhostSystemConstants.SnapshotHistorySize, Allocator.Temp); var baselinePerEntity = new NativeArray <int>(maxCount * 3, Allocator.Temp); for (int pc = 0; pc < serialChunks.Length && dataStream.Length < TargetPacketSize; ++pc) { var chunk = serialChunks[pc].chunk; var ghostType = serialChunks[pc].ghostType; Entity * currentSnapshotEntity = null; byte * currentSnapshotData = null; SerializationState chunkState; int dataSize = 0; availableBaselines.Clear(); if (chunkSerializationData.TryGetValue(chunk, out chunkState)) { dataSize = serializers.GetSnapshotSize(chunkState.ghostType); uint *snapshotIndex = (uint *)chunkState.snapshotData; snapshotIndex[chunkState.snapshotWriteIndex] = currentTick; int baseline = (GhostSystemConstants.SnapshotHistorySize + chunkState.snapshotWriteIndex - 1) % GhostSystemConstants.SnapshotHistorySize; while (baseline != chunkState.snapshotWriteIndex) { if (snapshotAck.IsReceivedByRemote(snapshotIndex[baseline])) { byte *dataBase = chunkState.snapshotData + UnsafeUtility.SizeOf <int>() * GhostSystemConstants.SnapshotHistorySize + baseline * (dataSize + entitySize) * chunk.Capacity; availableBaselines.Add(new SnapshotBaseline { tick = snapshotIndex[baseline], snapshot = dataBase + entitySize * chunk.Capacity, entity = (Entity *)(dataBase) }); } baseline = (GhostSystemConstants.SnapshotHistorySize + baseline - 1) % GhostSystemConstants.SnapshotHistorySize; } // Find the acked snapshot to delta against, setup pointer to current and previous entity* and data* // Remember to bump writeIndex when done currentSnapshotData = chunkState.snapshotData + UnsafeUtility.SizeOf <int>() * GhostSystemConstants.SnapshotHistorySize; currentSnapshotData += chunkState.snapshotWriteIndex * (dataSize + entitySize) * chunk.Capacity; currentSnapshotEntity = (Entity *)currentSnapshotData; currentSnapshotData += entitySize * chunk.Capacity; } var ghosts = serialChunks[pc].ghostState; if (ghosts == null) { ghosts = (GhostSystemStateComponent *)chunk.GetNativeArray(ghostSystemStateType).GetUnsafeReadOnlyPtr(); } var ghostEntities = chunk.GetNativeArray(entityType); int ent; if (serialChunks[pc].startIndex < chunk.Count) { dataStream.WritePackedUInt((uint)ghostType, compressionModel); dataStream.WritePackedUInt((uint)(chunk.Count - serialChunks[pc].startIndex), compressionModel); } // First figure out the baselines to use per entity so they can be sent as baseline + maxCount instead of one per entity int targetBaselines = serializers.WantsPredictionDelta(ghostType) ? 3 : 1; for (ent = serialChunks[pc].startIndex; ent < chunk.Count; ++ent) { int foundBaselines = 0; for (int baseline = 0; baseline < availableBaselines.Length; ++baseline) { if (availableBaselines[baseline].entity[ent] == ghostEntities[ent]) { baselinePerEntity[ent * 3 + foundBaselines] = baseline; ++foundBaselines; if (foundBaselines == targetBaselines) { break; } } // Only way an entity can be missing from a snapshot but be available in an older is if last snapshot was partial else if (availableBaselines[baseline].entity[ent] != Entity.Null) { break; } } if (foundBaselines == 2) { foundBaselines = 1; } while (foundBaselines < 3) { baselinePerEntity[ent * 3 + foundBaselines] = -1; ++foundBaselines; } } ent = serializers.Serialize(ghostType, chunk, serialChunks[pc].startIndex, currentTick, currentSnapshotEntity, currentSnapshotData, ghosts, ghostEntities, baselinePerEntity, availableBaselines, dataStream, compressionModel); updateLen += (uint)(ent - serialChunks[pc].startIndex); // Spawn chunks are temporary and should not be added to the state data cache if (serialChunks[pc].ghostState == null) { // Only append chunks which contain data if (ent > serialChunks[pc].startIndex) { if (serialChunks[pc].startIndex > 0) { UnsafeUtility.MemClear(currentSnapshotEntity, entitySize * serialChunks[pc].startIndex); } if (ent < chunk.Capacity) { UnsafeUtility.MemClear(currentSnapshotEntity + ent, entitySize * (chunk.Capacity - ent)); } chunkState.snapshotWriteIndex = (chunkState.snapshotWriteIndex + 1) % GhostSystemConstants.SnapshotHistorySize; } if (ent >= chunk.Count) { chunkState.lastUpdate = currentTick; chunkState.startIndex = 0; } else { // TODO: should this always be run or should partial chunks only be allowed for the highest priority chunk? //if (pc == 0) chunkState.startIndex = ent; } chunkSerializationData.Remove(chunk); chunkSerializationData.TryAdd(chunk, chunkState); } } dataStream.Flush(); despawnLenWriter.Update(despawnLen); updateLenWriter.Update(updateLen); driver.Send(unreliablePipeline, connectionFromEntity[connectionEntity].Value, dataStream); }
private static extern int Decrypt(byte* output, byte* input, long inputLength, byte* nonce, byte* secret);
// // After PInvoke call the method will fix the handleTemplate.handle with the returned value. // The caller is responsible for creating a correct SafeFreeContextBuffer_XXX flavour or null can be passed if no handle is returned. // private static unsafe int MustRunInitializeSecurityContext_SECURITY( ref SafeFreeCredentials inCredentials, void* inContextPtr, byte* targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness endianness, Interop.Secur32.SecurityBufferDescriptor inputBuffer, SafeDeleteContext outContext, Interop.Secur32.SecurityBufferDescriptor outputBuffer, ref Interop.Secur32.ContextFlags attributes, SafeFreeContextBuffer handleTemplate) { int errorCode = (int)Interop.SecurityStatus.InvalidHandle; try { bool ignore = false; inCredentials.DangerousAddRef(ref ignore); outContext.DangerousAddRef(ref ignore); Interop.Secur32.SSPIHandle credentialHandle = inCredentials._handle; long timeStamp; errorCode = Interop.Secur32.InitializeSecurityContextW( ref credentialHandle, inContextPtr, targetName, inFlags, 0, endianness, inputBuffer, 0, ref outContext._handle, outputBuffer, ref attributes, out timeStamp); } finally { // // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. // If the credential handle has been changed we de-ref the old one and associate the // context with the new cred handle but only if the call was successful. if (outContext._EffectiveCredential != inCredentials && (errorCode & 0x80000000) == 0) { // Disassociate the previous credential handle if (outContext._EffectiveCredential != null) { outContext._EffectiveCredential.DangerousRelease(); } outContext._EffectiveCredential = inCredentials; } else { inCredentials.DangerousRelease(); } outContext.DangerousRelease(); } // The idea is that SSPI has allocated a block and filled up outUnmanagedBuffer+8 slot with the pointer. if (handleTemplate != null) { //ATTN: on 64 BIT that is still +8 cause of 2* c++ unsigned long == 8 bytes handleTemplate.Set(((Interop.Secur32.SecurityBufferStruct*)outputBuffer.UnmanagedPointer)->token); if (handleTemplate.IsInvalid) { handleTemplate.SetHandleAsInvalid(); } } if (inContextPtr == null && (errorCode & 0x80000000) != 0) { // an error on the first call, need to set the out handle to invalid value outContext._handle.SetToInvalid(); } return errorCode; }
private static int Decrypt(byte* output, byte* input, long inputLength, byte[] nonce, byte[] secret) { return -1; }
private static unsafe string EncodeObject(ref object data, EventData *dataDescriptor, byte *dataBuffer) /*++ * * Routine Description: * * This routine is used by WriteEvent to unbox the object type and * to fill the passed in ETW data descriptor. * * Arguments: * * data - argument to be decoded * * dataDescriptor - pointer to the descriptor to be filled * * dataBuffer - storage buffer for storing user data, needed because cant get the address of the object * * Return Value: * * null if the object is a basic type other than string. String otherwise * * --*/ { dataDescriptor->Reserved = 0; string sRet = data as string; if (sRet != null) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return(sRet); } if (data == null) { dataDescriptor->Size = 0; dataDescriptor->DataPointer = 0; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr *intptrPtr = (IntPtr *)dataBuffer; * intptrPtr = (IntPtr)data; dataDescriptor->DataPointer = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int *intptrPtr = (int *)dataBuffer; * intptrPtr = (int)data; dataDescriptor->DataPointer = (ulong)intptrPtr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long *longptr = (long *)dataBuffer; * longptr = (long)data; dataDescriptor->DataPointer = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint *uintptr = (uint *)dataBuffer; * uintptr = (uint)data; dataDescriptor->DataPointer = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64 *ulongptr = (ulong *)dataBuffer; * ulongptr = (ulong)data; dataDescriptor->DataPointer = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char *charptr = (char *)dataBuffer; * charptr = (char)data; dataDescriptor->DataPointer = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte *byteptr = (byte *)dataBuffer; * byteptr = (byte)data; dataDescriptor->DataPointer = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short *shortptr = (short *)dataBuffer; * shortptr = (short)data; dataDescriptor->DataPointer = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte *sbyteptr = (sbyte *)dataBuffer; * sbyteptr = (sbyte)data; dataDescriptor->DataPointer = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort *ushortptr = (ushort *)dataBuffer; * ushortptr = (ushort)data; dataDescriptor->DataPointer = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float *floatptr = (float *)dataBuffer; * floatptr = (float)data; dataDescriptor->DataPointer = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double *doubleptr = (double *)dataBuffer; * doubleptr = (double)data; dataDescriptor->DataPointer = (ulong)doubleptr; } else if (data is bool) { dataDescriptor->Size = (uint)sizeof(bool); bool *boolptr = (bool *)dataBuffer; * boolptr = (bool)data; dataDescriptor->DataPointer = (ulong)boolptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid *guidptr = (Guid *)dataBuffer; * guidptr = (Guid)data; dataDescriptor->DataPointer = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal *decimalptr = (decimal *)dataBuffer; * decimalptr = (decimal)data; dataDescriptor->DataPointer = (ulong)decimalptr; } else if (data is Boolean) { dataDescriptor->Size = (uint)sizeof(Boolean); Boolean *booleanptr = (Boolean *)dataBuffer; * booleanptr = (Boolean)data; dataDescriptor->DataPointer = (ulong)booleanptr; } else { //To our eyes, everything else is a just a string sRet = data.ToString(); dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return(sRet); } return(null); }
/// <summary> /// The GetBytes. /// </summary> /// <param name="obj">The obj<see cref="IList"/>.</param> /// <param name="forKeys">The forKeys<see cref="bool"/>.</param> /// <returns>The <see cref="Byte[]"/>.</returns> public unsafe static Byte[] GetBytes(this IList obj, bool forKeys = false) { int length = 256, offset = 0, postoffset = 0, count = obj.Count, charsize = sizeof(char), s = 0; byte *buffer = stackalloc byte[length]; bool toResize = false; for (int i = 0; i < count; i++) { object o = obj[i]; if (o is string) { string str = ((string)o); s = str.Length * charsize; postoffset = (s + offset); if (postoffset > length) { toResize = true; } else fixed(char *c = str) Extractor.CopyBlock(buffer, (byte *)c, offset, s); } else { if (o is IUnique) { s = 8; postoffset = (s + offset); if (postoffset > length) { toResize = true; } else { *((ulong *)(buffer + offset)) = ((IUnique)o).UniqueKey; } } else { s = o.GetSize(); postoffset = (s + offset); if (postoffset > length) { toResize = true; } else { Extractor.StructureToPointer(o, new IntPtr(buffer + offset)); } } } if (toResize) { i--; toResize = false; byte *_buffer = stackalloc byte[postoffset]; Extractor.CopyBlock(_buffer, buffer, offset); buffer = _buffer; length = postoffset; } else { offset = postoffset; } } byte[] result = new byte[offset]; fixed(byte *result_p = result) { Extractor.CopyBlock(result_p, buffer, offset); } return(result); }
private void Read(IntPtr handle, long offset, int length, byte *buffer) { var ioStatus = new IO_STATUS_BLOCK(); mHooks.NtReadFileHook.OriginalFunction(handle, IntPtr.Zero, null, null, ref ioStatus, buffer, ( uint )length, (LARGE_INTEGER *)&offset, IntPtr.Zero); }
/// <summary> /// The StructureTo. /// </summary> /// <param name="structure">The structure<see cref="object"/>.</param> /// <param name="binary">The binary<see cref="byte*"/>.</param> public unsafe static void StructureTo(this object structure, byte *binary) { Extractor.StructureToPointer(structure, binary); }
internal Indexer(Mat parent) : base(parent) { ptr = (byte *)parent.Data.ToPointer(); }
/// <summary> /// The StructureFrom. /// </summary> /// <param name="structure">The structure<see cref="object"/>.</param> /// <param name="binary">The binary<see cref="byte*"/>.</param> /// <returns>The <see cref="object"/>.</returns> public unsafe static object StructureFrom(this object structure, byte *binary) { return(Extractor.PointerToStructure(binary, structure)); }
public void Dispose() { _inputBitmap.UnlockBits(_bitmapData); _bitmapData = null; _pBase = null; }
/// <summary> /// Installs an Import Address Table (IAT) hook. /// You choose a function (<paramref name="sFuncMod"/>, <paramref name="sFuncName"/>) whose entry will be replaced in the IAT of the specified module (<paramref name="sCallingMod"/>) to point to your own implementation (<see cref="pNewFunction"/>) instead. /// </summary> /// <param name="sFuncMod">Name of the module in which the function-to-be-hooked is defined. Example: <c>USER32.DLL</c>.</param> /// <param name="sFuncName">Name of the function to be hooked. Example: <c>SystemParametersInfoW</c>. Note that for the functions that have separate ANSI and Wide versions you must include a suffix in the function name. Must have the <c>stdcall</c> (<c>WINAPI</c>, <c>PASCAL</c>) calling convention.</param> /// <param name="sCallingMod">The module whose IAT is to be patched. Its calls to the Function will be intercepted. Must be loadable with <c>LoadLibrary</c> (or already loaded).</param> /// <param name="pNewFunction">The new implementation to replace the Function, in view of <paramref name"sCallingMod"/>. The hook will hold a reference on the delegate. Note that it's up to you to provide the appropriate signature of the delegate, which must match the one of the Function. Pay attention to the charset and bitness issues.</param> public static void Install([NotNull] string sFuncMod, [NotNull] string sFuncName, [NotNull] string sCallingMod, [NotNull] Delegate pNewFunction) { if (sFuncMod == null) { throw new ArgumentNullException("sFuncMod"); } if (sFuncName == null) { throw new ArgumentNullException("sFuncName"); } if (sCallingMod == null) { throw new ArgumentNullException("sCallingMod"); } if (pNewFunction == null) { throw new ArgumentNullException("pNewFunction"); } void *hmodCaller = UnsafeNativeMethods.LoadLibraryW(sCallingMod); if (Marshal.GetLastWin32Error() != 0) { throw new InvalidOperationException(string.Format("Could not load the module {0}.", sCallingMod.QuoteIfNeeded()), new Win32Exception()); } if (hmodCaller == null) { throw new InvalidOperationException(string.Format("Could not load the module {0}.", sCallingMod.QuoteIfNeeded())); } void *hmodFunc = UnsafeNativeMethods.GetModuleHandleW(sFuncMod); if (Marshal.GetLastWin32Error() != 0) { throw new InvalidOperationException(string.Format("Could not load the module {0}.", sFuncMod.QuoteIfNeeded()), new Win32Exception()); } if (hmodFunc == null) { throw new InvalidOperationException(string.Format("Could not load the module {0}.", sFuncMod.QuoteIfNeeded())); } void *pFunc = UnsafeNativeMethods.GetProcAddress(hmodFunc, sFuncName); if (Marshal.GetLastWin32Error() != 0) { throw new InvalidOperationException(string.Format("Could not locate the {0} function in the {1} module.", sFuncName.QuoteIfNeeded(), sFuncMod.QuoteIfNeeded()), new Win32Exception()); } if (pFunc == null) { throw new InvalidOperationException(string.Format("Could not locate the {0} function in the {1} module.", sFuncName.QuoteIfNeeded(), sFuncMod.QuoteIfNeeded())); } uint ulSize; // Look for the imports section void *pImportDescVoid = UnsafeNativeMethods.ImageDirectoryEntryToData(hmodCaller, 1, UnsafeNativeMethods.IMAGE_DIRECTORY_ENTRY_IMPORT, out ulSize); if (Marshal.GetLastWin32Error() != 0) { throw new InvalidOperationException(string.Format("Could not locate the import address table for the {0} module.", sCallingMod.QuoteIfNeeded()), new Win32Exception()); } if (pImportDescVoid == null) { throw new InvalidOperationException(string.Format("Could not locate the import address table for the {0} module.", sCallingMod.QuoteIfNeeded())); } // Find the entry for the function's module, look by its name var bytes = new List <byte>(); var pImportDesc = (UnsafeNativeMethods.IMAGE_IMPORT_DESCRIPTOR *)pImportDescVoid; int nCount; for (nCount = 0; (pImportDesc->Name != 0) && (nCount < IterationLimit); pImportDesc++, nCount++) { byte *szModName = (byte *)hmodCaller + pImportDesc->Name; // RVA bytes.Clear(); for (int a = 0; (a < 0x100) && (szModName[a] != 0); a++) { bytes.Add(szModName[a]); } string sModName = Encoding.Default.GetString(bytes.ToArray()); if (string.Compare(sModName, sFuncMod, StringComparison.InvariantCultureIgnoreCase) == 0) { break; } } if (!((pImportDesc->Name != 0) && (nCount < IterationLimit))) // Gotten to the end { throw new InvalidOperationException(string.Format("Could not find an entry for the {0} module in the import address table of the {1} module.", sFuncMod, sCallingMod)); } // Look for all the functions imported by the calling module from the function's module // Tell our Function apart by its address, as gotten from GetProcAddress var pThunk = (UnsafeNativeMethods.IMAGE_THUNK_DATA *)((byte *)hmodCaller + pImportDesc->FirstThunk); // RVA for (nCount = 0; (pThunk->Function != null) && (nCount < IterationLimit); pThunk++, nCount++) { void **ppfn = &pThunk->Function; if (*ppfn == pFunc) { var mbi = new UnsafeNativeMethods.MEMORY_BASIC_INFORMATION(); IntPtr nBytesReturned = UnsafeNativeMethods.VirtualQuery(ppfn, ref mbi, (IntPtr)Marshal.SizeOf(typeof(UnsafeNativeMethods.MEMORY_BASIC_INFORMATION))); if ((nBytesReturned == IntPtr.Zero) && (Marshal.GetLastWin32Error() != 0)) // Note: sometimes it would state "file not found" without any good reason { throw new InvalidOperationException("Could not query for the memory protection information.", new Win32Exception()); } // Lift the memory protection if (UnsafeNativeMethods.VirtualProtect(mbi.BaseAddress, mbi.RegionSize, UnsafeNativeMethods.PAGE_READWRITE, out mbi.Protect) == 0) { throw new InvalidOperationException(string.Format("Could not unlock import address table memory.")); } // Hold a reference to the delegate (otherwise the pointer we create will be lost after the delegate gets collected) DelegateAddRef(pNewFunction); // This is it *ppfn = (void *)Marshal.GetFunctionPointerForDelegate(pNewFunction); // Restore the protection uint dwOldProtect; UnsafeNativeMethods.VirtualProtect(mbi.BaseAddress, mbi.RegionSize, mbi.Protect, out dwOldProtect); break; // Done! } } if (!((pThunk->Function != null) && (nCount < IterationLimit))) // No such func (btw may so happen we've already hooked it) { throw new InvalidOperationException(string.Format("Could not find the {0} function from the {1} module in the import address table of the {2} module.", sFuncName, sFuncMod, sCallingMod)); } }