Archive for 5月 2nd, 2012

  1. Hello, Win32 API(JNA) World!

    Posted on 5月 2nd, 2012 by cx20

    Win32 API(JNA)

    Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
    以下は JNA(Java Native Access)による呼出し例である。

    ソースコード

    import com.sun.jna.Native;
    import com.sun.jna.win32.StdCallLibrary;
     
    public class Hello {
        public interface User32 extends StdCallLibrary {
            User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);
            int MessageBoxA(int hwnd, String text, String caption, int type);
        }
     
        public static void main(String[] args) {
            User32 user32 = User32.INSTANCE;
            user32.MessageBoxA(0, "Hello, Win32 API(JNA) World!", "Hello, World!", 0);
        }
    }

    Win32 データ型と JNA データ型の対応は主に以下のようになっている。

    Win32 データ型 C/C++ データ型 Java/JNA データ型
    BYTE char byte
    SHORT short short
    WCHAR wchar_t char
    INT int int
    BOOL int boolean
    LONG long NativeLong(JNA データ型)
    LONGLONG __int64 long
    FLOAT float float
    DOUBLE double double
    LPCSTR const char * String
    LPCWSTR const wchar_t * WString(JNA データ型)
    LPINT int * IntByReference(JNA データ型)
    LPVOID void * Pointer

    コンパイル&実行方法

    C:¥> javac -cp jna.jar;. Hello.java
    C:¥> java -cp jna.jar;. Hello

    実行結果

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