Created
January 11, 2018 07:33
-
-
Save stwiname/1b64c4e72a64e1be764e4d3751424937 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/* | |
#cgo LDFLAGS: -lpthread -Llibrary -ltesting | |
#include "library/testing.h" | |
extern void cgo_callback_wrapper(void * context, char *message, int message_len); | |
*/ | |
import "C" | |
import ( | |
"fmt" | |
"sync" | |
"unsafe" | |
) | |
var registry map[int]Handler | |
var handlers int | |
var mutex = sync.Mutex{} | |
type Handler interface { | |
HandleMessage([]byte) | |
} | |
type Publisher struct { | |
base *C.struct_publisher | |
} | |
//export callbackWrapper | |
func callbackWrapper(cContext unsafe.Pointer, cMessage *C.char, cMessageSize C.int) { | |
mutex.Lock() | |
handler := registry[*(*int)(cContext)] | |
mutex.Unlock() | |
message := C.GoBytes(unsafe.Pointer(cMessage), cMessageSize) | |
handler.HandleMessage(message) | |
} | |
func (p *Publisher) Publish(message []byte) { | |
cMessage := (*C.char)(unsafe.Pointer(&message[0])) | |
cMessageLen := C.int(len(message)) | |
C.publisher_publish(p.base, cMessage, cMessageLen) | |
} | |
func CreatePublisher(handler Handler) *Publisher { | |
mutex.Lock() | |
index := handlers | |
handlers++ | |
if registry == nil { | |
registry = make(map[int]Handler) | |
} | |
registry[index] = handler | |
mutex.Unlock() | |
return &Publisher{ | |
base: C.publisher_new(unsafe.Pointer(&index), (*[0]byte)(C.cgo_callback_wrapper)), | |
} | |
} | |
func (p *Publisher) Finish() { | |
C.publisher_finish(p.base) | |
} | |
//////// EXAMPLE //////// | |
type TestHandler struct { | |
name string | |
} | |
func (h TestHandler) HandleMessage(message []byte) { | |
fmt.Printf("%s received %v", h.name, message) | |
} | |
func main() { | |
handler := TestHandler{name: "Test"} | |
publisher := CreatePublisher(handler) | |
publisher.Publish([]byte("test")) | |
publisher.Finish() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment