github.com/wencode/hack@v0.2.9/dl/dl_unix.go (about)

     1  // +build linux darwin
     2  
     3  package dl
     4  
     5  // #include <dlfcn.h>
     6  // #include <stdlib.h>
     7  // #include <string.h>
     8  // #cgo LDFLAGS: -ldl -pthread
     9  import "C"
    10  import (
    11  	"unsafe"
    12  )
    13  
    14  func Open(filename string) (lib Lib, err error) {
    15  	s := C.CString(filename)
    16  	defer C.free(unsafe.Pointer(s))
    17  
    18  	handle, e := C.dlopen(s, C.RTLD_NOW)
    19  	if handle == nil {
    20  		err = newDLError(filename, e)
    21  		return
    22  	}
    23  	lib = Lib(uintptr(handle))
    24  	return
    25  }
    26  
    27  func (lib Lib) Close() {
    28  	C.dlclose(unsafe.Pointer(lib))
    29  }
    30  
    31  func (lib Lib) Sym(symbol string) uintptr {
    32  	s := C.CString(symbol)
    33  	defer C.free(unsafe.Pointer(s))
    34  
    35  	addr := C.dlsym(unsafe.Pointer(lib), s)
    36  	return uintptr(addr)
    37  }
    38  
    39  func newDLError(filename string, err error) *DLError {
    40  	return &DLError{
    41  		filename:filename,
    42  		errstr: err.Error(),
    43  	}
    44  }