static void ProtectionSafeMemoryCopy(IntPtr dest, IntPtr source, int count) { // UIntPtr = size_t var bufferSize = new UIntPtr((uint)count); Enums.VirtualProtectionType oldProtection, temp; // unprotect memory to copy buffer if (!NativeImport.VirtualProtect(dest, bufferSize, Enums.VirtualProtectionType.ExecuteReadWrite, out oldProtection)) { throw new Exception("Failed to unprotect memory."); } byte *pDest = (byte *)dest; byte *pSrc = (byte *)source; // copy buffer to address for (int i = 0; i < count; i++) { *(pDest + i) = *(pSrc + i); } // protect back if (!NativeImport.VirtualProtect(dest, bufferSize, oldProtection, out temp)) { throw new Exception("Failed to protect memory."); } }
/// <summary> /// Allocates a console instance to the running process /// </summary> internal static void CreateLoggerInstance() { NativeImport.AllocConsole(); var outFile = NativeImport.CreateFile("CONOUT$", NativeImport.ConsolePropertyModifiers.GENERIC_WRITE | NativeImport.ConsolePropertyModifiers.GENERIC_READ, NativeImport.ConsolePropertyModifiers.FILE_SHARE_WRITE, 0, NativeImport.ConsolePropertyModifiers.OPEN_EXISTING, /*FILE_ATTRIBUTE_NORMAL*/ 0, 0); var safeHandle = new SafeFileHandle(outFile, true); NativeImport.SetStdHandle(-11, outFile); FileStream fs = new FileStream(safeHandle, FileAccess.Write); StreamWriter writer = new StreamWriter(fs) { AutoFlush = true }; Console.SetOut(writer); if (NativeImport.GetConsoleMode(outFile, out var cMode)) { NativeImport.SetConsoleMode(outFile, cMode | 0x0200); } Console.Title = $"Log Window - {Assembly.GetExecutingAssembly().GetName().Name}"; }