问题
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