github.com/kitech/dl@v0.0.0-20201225001532-be4f4faa4070/dl.go (about) 1 package dl 2 3 // #include <stdlib.h> 4 // #include <dlfcn.h> 5 // #cgo LDFLAGS: -ldl 6 import "C" 7 8 import ( 9 "fmt" 10 "unsafe" 11 ) 12 13 type Flags int 14 15 const ( 16 Lazy Flags = C.RTLD_LAZY 17 Now Flags = C.RTLD_NOW 18 Global Flags = C.RTLD_GLOBAL 19 Local Flags = C.RTLD_LOCAL 20 //NoLoad Flags = C.RTLD_NOLOAD 21 //NoDelete Flags = C.RTLD_NODELETE 22 // First Flags = C.RTLD_FIRST 23 ) 24 25 type Handle struct { 26 c unsafe.Pointer 27 } 28 29 func Open(fname string, flags Flags) (Handle, error) { 30 c_str := C.CString(fname) 31 defer C.free(unsafe.Pointer(c_str)) 32 33 h := C.dlopen(c_str, C.int(flags)) 34 if h == nil { 35 c_err := C.dlerror() 36 return Handle{}, fmt.Errorf("dl: %s", C.GoString(c_err)) 37 } 38 return Handle{h}, nil 39 } 40 41 func (h Handle) Close() error { 42 o := C.dlclose(h.c) 43 if o != C.int(0) { 44 c_err := C.dlerror() 45 return fmt.Errorf("dl: %s", C.GoString(c_err)) 46 } 47 return nil 48 } 49 50 func (h Handle) Addr() uintptr { 51 return uintptr(h.c) 52 } 53 54 func (h Handle) Symbol(symbol string) (uintptr, error) { 55 c_sym := C.CString(symbol) 56 defer C.free(unsafe.Pointer(c_sym)) 57 58 c_addr := C.dlsym(h.c, c_sym) 59 if c_addr == nil { 60 c_err := C.dlerror() 61 return 0, fmt.Errorf("dl: %s", C.GoString(c_err)) 62 } 63 return uintptr(c_addr), nil 64 } 65 66 // /* Portable libltdl versions of the system dlopen() API. */ 67 // LT_SCOPE lt_dlhandle lt_dlopen (const char *filename); 68 // LT_SCOPE lt_dlhandle lt_dlopenext (const char *filename); 69 // LT_SCOPE lt_dlhandle lt_dlopenadvise (const char *filename, 70 // lt_dladvise advise); 71 // LT_SCOPE void * lt_dlsym (lt_dlhandle handle, const char *name); 72 // LT_SCOPE const char *lt_dlerror (void); 73 // LT_SCOPE int lt_dlclose (lt_dlhandle handle); 74 75 // EOF