duanfu6160 2014-06-09 21:44
浏览 97
已采纳

带有golang的Windows挂钩

I'm writing an application that will make use of the Win32 API WH_KEYBOARD hook so that it can be activated (i.e., displayed in the foreground) without having focus. The callback, naturally, is a function pointer (of type HOOKPROC). A lot of the documentation for WH_KEYBOARD and WH_KEYBOARD_LL says that the callback has to reside in a DLL and cannot directly be in an EXE, however I've found that not to be true in Windows XP and above so I think that's a historical quirk.

The application is written in Go. I'm aware of (and have contributed to) github.com/AllenDang/w32, but I don't see anything that can be used to deal with function pointers. Due to the structure of goroutines, is this even possible? I know that calling C from Go is simple, but what does one do about function pointers for callbacks like this?

Right now my kludge is to write an EXE that sends a message via the standard output, compile it separately, include it using go-bindata and at runtime write this to a temporary file and execute it, while a goroutine watches that process's standard output. It makes me cringe. Please tell me there's a better way without using an external process and awful IPC hackery.

  • 写回答

1条回答 默认 最新

  • donglv9813 2014-06-09 22:02
    关注

    Read the wiki page about cgo.

    You will have to define the callback in C and then call your Go function from it:

    First export your Go callback :

    //export gocb
    func gocb() {
    
    }
    

    Then define your callback in say hook.c

    #include "_cgo_export.h"
    
    void c_callback() {
        gocb();
    }
    

    It's my code and I hacked it up to test something, never had the time to clean it up after that.

    Here's an (ugly ugly) example: https://github.com/OneOfOne/go-nfqueue/blob/master/nfqueue.go#L129, https://github.com/OneOfOne/go-nfqueue/blob/master/nfqueue.h and https://github.com/OneOfOne/go-nfqueue/blob/master/nfqueue.c#L49

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题