Calling functions in an so file from Go

淺唱寂寞╮ 提交于 2019-12-04 23:48:22

问题


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



来源:https://stackoverflow.com/questions/27506579/calling-functions-in-an-so-file-from-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!