-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcgo.go
98 lines (81 loc) · 2.35 KB
/
cgo.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
97
98
// A pacakge that exports Decred wallet functionalities as go code that can be
// compiled into a c-shared libary. Must be a main package, with an empty main
// function. And functions to be exported must have an "//export {fnName}"
// comment.
//
// Build cmd: go build -buildmode=c-archive -o {path_to_generated_library} ./cgo
// E.g. go build -buildmode=c-archive -o ./build/libdcrwallet.a ./cgo.
package main
import "C"
import (
"context"
"sync"
"github.com/decred/libwallet/asset/dcr"
"github.com/decred/libwallet/assetlog"
"github.com/decred/slog"
)
var (
mainCtx context.Context
cancelMainCtx context.CancelFunc
wg sync.WaitGroup
logBackend *parentLogger
logMtx sync.RWMutex
log slog.Logger
// walletsMtx protects wallets and initialized.
walletsMtx sync.RWMutex
wallets = make(map[string]*wallet)
initialized bool
)
//export initialize
func initialize(cLogDir *C.char) *C.char {
walletsMtx.Lock()
defer walletsMtx.Unlock()
if initialized {
return errCResponse("duplicate initialization")
}
logDir := goString(cLogDir)
logSpinner, err := assetlog.NewRotator(logDir, "dcrwallet.log")
if err != nil {
return errCResponse("error initializing log rotator: %v", err)
}
logBackend = newParentLogger(logSpinner)
err = dcr.InitGlobalLogging(logDir, logBackend)
if err != nil {
return errCResponse("error initializing logger for external pkgs: %v", err)
}
logMtx.Lock()
log = logBackend.SubLogger("[APP]")
log.SetLevel(slog.LevelTrace)
logMtx.Unlock()
mainCtx, cancelMainCtx = context.WithCancel(context.Background())
initialized = true
return successCResponse("libwallet cgo initialized")
}
//export shutdown
func shutdown() *C.char {
logMtx.RLock()
log.Debug("libwallet cgo shutting down")
logMtx.RUnlock()
walletsMtx.Lock()
defer walletsMtx.Unlock()
if !initialized {
return errCResponse("not initialized")
}
for _, wallet := range wallets {
if err := wallet.CloseWallet(); err != nil {
wallet.log.Errorf("close wallet error: %v", err)
}
}
wallets = make(map[string]*wallet)
// Stop all remaining background processes and wait for them to stop.
cancelMainCtx()
wg.Wait()
// Close the logger backend as the last step.
logMtx.Lock()
log.Debug("libwallet cgo shutdown")
logBackend.Close()
logMtx.Unlock()
initialized = false
return successCResponse("libwallet cgo shutdown")
}
func main() {}