Example #1
0
        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.");
            }
        }