How can I call linux shared library functions in Go?

人走茶凉 提交于 2020-05-13 04:12:06

问题


I have a .so file whose functions I would like to call in my Go code.

How do I go about doing that ? I have read the cgo and syscall package. They are close to what I want but I don't see any place where I can call the functions in the .so file.

I want to achieve exactly what the ctypes package does in Python.

Can somebody help ?


回答1:


If you want to use a shared library that is known statically at compile time, you can simply use cgo. Read the documentation on how to do that exactly, but usually you specify some linker flags and a couple of commented out lines. Here is an example on how to call function bar() from libfoo.so.

package example

// #cgo LDFLAGS: -lfoo
//
// #include <foo.h>
import "C"

func main() {
    C.bar()
}

You can also use cgo to access shared objects that are being loaded dynamically at runtime. You can use dlopen(), dlsym(), and dlclose() to open a shared library, retrieve the address of one of the functions inside and finally close the library. Notice that you can't do these things in Go, you have to write some wrapper code in C that implements the neccessary logic for you.



来源:https://stackoverflow.com/questions/24149299/how-can-i-call-linux-shared-library-functions-in-go

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