-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdummy.go
96 lines (79 loc) · 1.62 KB
/
dummy.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package glua
import (
"errors"
"fmt"
"reflect"
"sync"
"unsafe"
)
// #cgo CFLAGS: -I/usr/local/include/luajit-2.1
// #cgo LDFLAGS: -L/usr/local/lib -lluajit -ldl -lm
//#include "glua.h"
import "C"
type dummy struct {
key []byte
val interface{}
}
var (
dummyCache map[uintptr]map[uintptr]*dummy
dummyRW sync.RWMutex
)
func init() {
dummyCache = make(map[uintptr]map[uintptr]*dummy)
}
// lua dummy method
func pushDummy(vm *C.struct_lua_State, obj interface{}) unsafe.Pointer {
vmKey := generateLuaStateId(vm)
val := reflect.ValueOf(obj)
var (
realObj interface{}
dummyId uintptr
)
switch val.Kind() {
case reflect.Pointer:
{
realObj = val.Elem().Interface()
}
default:
{
realObj = obj
}
}
dObj := &dummy{
key: []byte(fmt.Sprintf("%p", &realObj)),
val: obj,
}
dummyId = uintptr(unsafe.Pointer(&(dObj.key[0])))
dummyRW.Lock()
target, ok := dummyCache[vmKey]
if false == ok {
target = make(map[uintptr]*dummy)
target[dummyId] = dObj
dummyCache[vmKey] = target
} else {
target[dummyId] = dObj
}
dummyRW.Unlock()
return unsafe.Pointer(dummyId)
}
func findDummy(vm *C.struct_lua_State, ptr unsafe.Pointer) (interface{}, error) {
vmKey := generateLuaStateId(vm)
dummyId := uintptr(ptr)
dummyRW.RLock()
defer dummyRW.RUnlock()
target, ok := dummyCache[vmKey]
if false == ok {
return nil, errors.New("Invalid VMKey")
}
dObj, ok := target[dummyId]
if false == ok {
return nil, errors.New("Invalid DummyId")
}
return dObj.val, nil
}
func cleanDummy(vm *C.struct_lua_State) {
vmKey := generateLuaStateId(vm)
dummyRW.Lock()
defer dummyRW.Unlock()
delete(dummyCache, vmKey)
}