...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package dlopen
18
19
20
21
22 import "C"
23 import (
24 "errors"
25 "fmt"
26 "unsafe"
27 )
28
29 var ErrSoNotFound = errors.New("unable to open a handle to the library")
30
31
32 type LibHandle struct {
33 Handle unsafe.Pointer
34 Libname string
35 }
36
37
38
39
40
41 func GetHandle(libs []string) (*LibHandle, error) {
42 for _, name := range libs {
43 libname := C.CString(name)
44 defer C.free(unsafe.Pointer(libname))
45 handle := C.dlopen(libname, C.RTLD_LAZY)
46 if handle != nil {
47 h := &LibHandle{
48 Handle: handle,
49 Libname: name,
50 }
51 return h, nil
52 }
53 }
54 return nil, ErrSoNotFound
55 }
56
57
58 func (l *LibHandle) GetSymbolPointer(symbol string) (unsafe.Pointer, error) {
59 sym := C.CString(symbol)
60 defer C.free(unsafe.Pointer(sym))
61
62 C.dlerror()
63 p := C.dlsym(l.Handle, sym)
64 e := C.dlerror()
65 if e != nil {
66 return nil, fmt.Errorf("error resolving symbol %q: %v", symbol, errors.New(C.GoString(e)))
67 }
68
69 return p, nil
70 }
71
72
73 func (l *LibHandle) Close() error {
74 C.dlerror()
75 C.dlclose(l.Handle)
76 e := C.dlerror()
77 if e != nil {
78 return fmt.Errorf("error closing %v: %v", l.Libname, errors.New(C.GoString(e)))
79 }
80
81 return nil
82 }
83
View as plain text