-
Notifications
You must be signed in to change notification settings - Fork 64
/
fake.go
58 lines (47 loc) · 973 Bytes
/
fake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cu
/*
#include <stdlib.h>
void handleCUDACB(void* v);
*/
import "C"
import (
"sync"
"unsafe"
)
// fake.go handles faking of C pointers of Go functions
var fakepointers = make(map[unsafe.Pointer]HostFunction)
var lock sync.RWMutex
// RegisterFunc is used to register a Go based callback such that it may be called by CUDA.
func RegisterFunc(fn HostFunction) unsafe.Pointer {
var ptr unsafe.Pointer = C.malloc(C.size_t(1))
if ptr == nil {
panic("Cannot allocate a fake pointer")
}
lock.Lock()
fakepointers[ptr] = fn
lock.Unlock()
return ptr
}
func getHostFn(ptr unsafe.Pointer) HostFunction {
if ptr == nil {
return nil
}
lock.RLock()
retVal := fakepointers[ptr]
lock.RUnlock()
return retVal
}
func deregisterFunc(ptr unsafe.Pointer) {
if ptr == nil {
return
}
lock.Lock()
delete(fakepointers, ptr)
lock.Unlock()
C.free(ptr)
}
//export handleCUDACB
func handleCUDACB(fn unsafe.Pointer) {
callback := getHostFn(fn)
callback()
}