Archive for 4月 28th, 2012

  1. Hello, Win32 API(Ruby) World!

    Posted on 4月 28th, 2012 by cx20

    Win32 API(Ruby)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は Ruby の Win32API ライブラリならびに Ruby/DL2(Ruby 1.9 より標準添付)よる呼出し例である。

    ソースコード(Win32API)

    require 'Win32API'
     
    msgbox = Win32API.new('user32', 'MessageBox', ['i', 'p', 'p', 'i'], 'i')
    msgbox.call( 0, "Hello, Win32 API(Ruby) World!", "Hello, World!", 0 )

    なお、上記の [‘i’, ‘p’, ‘p’, ‘i’], ‘i’ は、各引数と戻り値の型を表している。主なタイプとしては以下の種類がある。詳細は「Ruby 1.9.3 リファレンスマニュアル > ライブラリ一覧 > Win32APIライブラリ > Win32APIクラス」を参照のこと。

    タイプ 説明
    “p” ポインタ型(pointer)
    “l” 数値型(long)
    “i” 整数型(integer)
    “v” void 型

    ソースコード(Ruby/DL2)

    require 'dl/import'
    require 'dl/types'
     
    module User32
      extend DL::Importer
      dlload 'user32'
     
      include DL::Win32Types
      extern 'int MessageBoxA(HWND, LPCSTR, LPCSTR, UINT)'
    end
     
    User32.MessageBoxA( 0, "Hello, Windows API(Ruby) World!", "Hello, World!", 0 )

    Ruby/DL2 では、C言語のプロトタイプ宣言を記述することにより、外部ライブラリの利用が可能となっている。

    実行方法

    C:¥> ruby hello.rb

    実行結果

    ---------------------------
    Hello, World!
    ---------------------------
    Hello, Win32 API(Ruby) World!
    ---------------------------
    OK   
    ---------------------------