简体   繁体   中英

Windows Hooks with golang

I'm writing an application that will make use of the Win32 API WH_KEYBOARD hook so that it can be activated (ie, 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM