RSS

タグ別アーカイブ: unsafe

C#: Win32 API の使い方

C# は unsafe キーワードを使って C 言語のコードを呼び出すことができる。Win32 API は 64ビット版 Windows でもそのまま使用できる。

その際の要件を下に示す。

  • Win32 API 関数の定義を示すクラスを用意する。
  • そのクラスでは System.Runtime.InteropServices 名前空間をインポートする。
  • 上記のクラスを使うコードは unsafe ブロックに含める。
  • ビルドの際には dotnet build /property:AllowUnsafeBlocks=true のように AllowUnsafeBlocks スイッチを有効にする。

次に具体的な例を示す。

Program.cs

// Win32 API
//  ビルド方法: dotnet build /property:AllowUnsafeBlocks=true
using Win32Api;

Action<Object> println = o => Console.WriteLine(o.ToString());
Action<String, Object> printf = (format, data) => Console.WriteLine(format, data);
Func<bool> isWindows = () => Environment.OSVersion.Platform == PlatformID.Win32NT;
Action<int> exit = code => Environment.Exit(code);

if (! isWindows())
{
  println("Error: Windows のみで実行可能。");
  exit(1);
}

// Win32 API の GlobalMemoryStatusEx() 関数を呼び出す。
unsafe
{
  Win32.MEMORYSTATUSEX buffer = new Win32.MEMORYSTATUSEX();
  buffer.dwLength = (uint)sizeof(Win32.MEMORYSTATUSEX);
  Win32.GlobalMemoryStatusEx(ref buffer);

  printf("物理メモリ総量 {0} バイト", buffer.ullTotalPhys);
}

Win32Api.cs

using System.Runtime.InteropServices;

// ディスクやメモリ情報を取得する Win32 API 関数を呼び出すためのクラス定義
namespace Win32Api
{
  class Win32
  {
     // ディスクやメモリ情報を受け取るための構造体
     public struct MEMORYSTATUSEX
     {
        public uint dwLength;
        public uint dwMemoryLoad;
        public ulong ullTotalPhys;
        public ulong ullAvailPhys;
        public ulong ullTotalPageFile;
        public ulong ullAvailPageFile;
        public ulong ullTotalVirtual;
        public ulong ullAvailVirtual;
        public ulong ullAvailExtendedVirtual;
     }

     // ィスクやメモリ情報を取得する Win32 API 関数
     [DllImport("kernel32.dll")]
     public static extern void GlobalMemoryStatusEx(ref MEMORYSTATUSEX Buffer);
    }
}
 
コメントする

投稿者: : 2024/04/29 投稿先 C#, dotNET

 

タグ: ,