Archive for 5月 6th, 2012
-
Hello, Win32 API(Go) World!
Posted on 5月 6th, 2012 by cx20
Win32 API(Go)
Win32 API は、Windows の機能にアクセスする為の API(Application Programming Interface)である。
以下は Go言語 にて syscall.Syscall 関数を用いた呼出し例である。ソースコード
package main import ( "syscall" "unsafe" ) var ( user32, _ = syscall.LoadLibrary("user32.dll") procMessageBoxW, _ = syscall.GetProcAddress(user32, "MessageBoxW") ) func MessageBox(hwnd uintptr, text string, caption string, style uintptr) (int32) { ret, _, _ := syscall.Syscall6( uintptr(procMessageBoxW), 4, hwnd, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(text))), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(caption))), style, 0, 0 ) return int32(ret) } func main() { defer syscall.FreeLibrary(user32) MessageBox( 0, "Hello, Win32 API(Go) World!", "Hello, World!", 0 ) }
Win32 データ型と Go言語 データ型の対応は主に以下のようになっている。
Win32 データ型 C/C++ データ型 Go データ型 HANDLE void * uintptr BYTE unsigned char uint8, byte SHORT short int16 WORD unsigned short uint16 INT int int32, int UINT unsigned int uint32 LONG long int32 BOOL int int DWORD unsigned long uint32 ULONG unsigned long uint32 CHAR char byte WCHAR wchar_t uint16 LPSTR char * *byte LPCSTR const char * *byte, syscall.StringByPtr() LPWSTR wchar_t * *uint16 LPCWSTR const wchar_t * *uint16, syscall.StringToUTF16Ptr() FLOAT float float32 DOUBLE double float64 LONGLONG __int64 int64 DWORD64 unsigned __int64 uint64 コンパイル方法
C:¥> SET GOROOT=C:go C:¥> go build -ldflags -Hwindowsgui hello.go
実行結果
--------------------------- Hello, World! --------------------------- Hello, Win32 API(Go) World! --------------------------- OK ---------------------------