2013-02-12 63 views
5

我想用下面的C作爲Go的CGO:去+ CGO和鏈接

#include <X11/extensions/scrnsaver.h> 

main() { 
    XScreenSaverInfo *info = XScreenSaverAllocInfo(); 
    Display *display = XOpenDisplay(0); 

    XScreenSaverQueryInfo(display, DefaultRootWindow(display), info); 
    printf("%u ms\n", info->idle); 
} 

構建具有:

gcc -o idle printXIdleTime.c -lX11 -lXss 

我重新寫了Go的CGO代碼:

package tools 

// #cgo pkg-config: x11 
// #include <X11/extensions/scrnsaver.h> 
import "C" 

func GetIdleTime() (idleTime uint32) { 
    var info *C.XScreenSaverInfo 
    var display *C.Display 

    info = C.XScreenSaverAllocInfo() 
    display = C.XOpenDisplay(0) 

    defaultRootWindow := C.XDefaultRootWindow(display) 

    C.XScreenSaverQueryInfo(display, defaultRootWindow, info) 
    idleTime = info.idle 

    return 
} 

試圖編譯:

go build -gccgoflags="-lXss -lX11" 

但是我得到的鏈接錯誤:

/tmp/go-build076004816/opensource.stdk/lib/tools/_obj/x11.cgo2.o: In function _cgo_c0e279f6f16e_Cfunc_XScreenSaverAllocInfo': ./x11.go:52: undefined reference to XScreenSaverAllocInfo' /tmp/go-build076004816/opensource.stdk/lib/tools/_obj/x11.cgo2.o: In function _cgo_c0e279f6f16e_Cfunc_XScreenSaverQueryInfo': ./x11.go:65: undefined reference to XScreenSaverQueryInfo' collect2: error: ld returned 1 exit status

我到底做錯了什麼?

回答

4

這就是我如何構建它。請注意0​​這一行可能是你錯過的。我必須做一些其他更改才能構建。它似乎在我的Linux機器上返回正確的答案!

package tools 

// #cgo LDFLAGS: -lXss -lX11 
// #include <X11/extensions/scrnsaver.h> 
import "C" 

func GetIdleTime() (idleTime uint32) { 
    var info *C.XScreenSaverInfo 
    var display *C.Display 

    info = C.XScreenSaverAllocInfo() 
    display = C.XOpenDisplay(nil) 

    defaultRootWindow := C.XDefaultRootWindow(display) 

    C.XScreenSaverQueryInfo(display, C.Drawable(defaultRootWindow), info) 
    idleTime = uint32(info.idle) 

    return 
} 
2

注意,這可能與本機X Go Binding和屏幕保護程序的擴展來完成:

package main 

import (
    "fmt" 
    "log" 

    "github.com/BurntSushi/xgb" 
    "github.com/BurntSushi/xgb/xproto" 
    "github.com/BurntSushi/xgb/screensaver" 
) 

func main() { 
    X, err := xgb.NewConn() 
    if err != nil { 
     log.Fatal(err) 
    } 

    if err = screensaver.Init(X); err != nil { 
     log.Fatal(err) 
    } 

    root := xproto.Setup(X).DefaultScreen(X).Root 
    info, err := screensaver.QueryInfo(X, xproto.Drawable(root)).Reply() 
    if err != nil { 
     log.Fatal(err) 
    } 

    fmt.Printf("Idle: %d\n", info.MsSinceUserInput) 
} 

輸出:

[[email protected] go] go run xscreensaver_idle.go 
Idle: 1040 
+0

與GOS XGB的問題是,如果我沒有我的家中的.XAuthority NewConn()失敗並顯示消息「無法連接」 – 2013-02-13 20:01:22

+0

XGB應該發出警告消息,但無論如何連接。你能否提交一份包含測試用例和環境描述的錯誤報告? https://github.com/BurntSushi/xgb/issues – BurntSushi5 2013-02-14 00:28:03