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 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch