Calling functions in an so file from Go

2019-03-28 09:45发布

问题:

Is it possible to call a static object (.so) file from Go? I've been searchign Google and I keep hitting upon the claim that I can do

lib, _ := syscall.LoadLibrary("...")

But trying this gives an error

undefined: syscall.LoadLibrary

and searching through Godocs I cannot find reference to this function in the syscall package. Is it possible to load a library and call its functions?

回答1:

On a POSIX platform, you could use cgo to call dlopen and friends:

// #cgo LDFLAGS: -ldl
// #include <dlfcn.h>
import "C"

import fmt

func foo() {
     handle := C.dlopen(C.CString("libfoo.so"), C.RTLD_LAZY)
     bar := C.dlsym(handle, C.CString("bar"))
     fmt.Printf("bar is at %p\n", bar)
}


回答2:

As @JimB said, you should just use CGO, and put the linking to the dynamic/static library there. as per this example:

// #cgo LDFLAGS: -lpng
// #include <png.h>
import "C"

...

var x:= C.png_whatever() // whatever the API is

Read more here: http://blog.golang.org/c-go-cgo