メモリークリーナ

追記
Win32APIをインポートしなくてもMarshalクラスにメモリ確保するメソッドがあります。参考:UnmanagedDoubleArray on C# - notes plastiques


モリークリーナの仕組みを調べたら意外と簡単だった。メモリを確保して、書き込んで開放してやるだけ。というわけで書いてみた。
コメントが沢山ありますが、中身はそんなにないんで; Main関数を見ると大体流れが分かる。

namespace Memory
{
    using System;
    using System.Runtime.InteropServices;
    internal class Memory
    {
        [DllImport("kernel32")]
        public static extern void FillMemory(IntPtr Destination, uint Length, byte Fill);
        private static void Main(string[] args)
        {
            uint FSize = uint.Parse(args[0]);
            Console.WriteLine("メモリ確保中… {0}MB", FSize);
            FSize *= 0x100000;
            IntPtr lpMem = VirtualAlloc(IntPtr.Zero, FSize, AllocationType.TOP_DOWN | AllocationType.COMMIT, ProtectType.NOCACHE | ProtectType.READWRITE);
            Console.WriteLine("Zeroを書き込み中…");
            FillMemory(lpMem, FSize, 0);
            Console.WriteLine("メモリ開放中…");
            VirtualFree(lpMem, FSize, FreeType.DECOMMIT);
            Console.WriteLine("開放完了。");
            Console.ReadKey(true);
        }

        [DllImport("kernel32")]
        public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, AllocationType flAllocationType, ProtectType flProtect);
        [DllImport("kernel32")]
        public static extern bool VirtualFree(IntPtr lpAddress, uint dwSize, FreeType dwFreeType);
    }
    public enum ProtectType
    {
        EXECUTE = 0x10,
        EXECUTE_READ = 0x20,
        EXECUTE_READWRITE = 0x40,
        GUARD = 0x100,
        NOACCESS = 1,
        NOCACHE = 0x200,
        READONLY = 2,
        READWRITE = 4
    }
    public enum FreeType
    {
        DECOMMIT = 0x4000,
        RELEASE = 0x8000
    }
    public enum AllocationType
    {
        COMMIT = 0x1000,
        PHYSICAL = 0x400000,
        RESERVE = 0x2000,
        RESET = 0x80000,
        TOP_DOWN = 0x100000,
        WRITE_WATCH = 0x200000
    }

}