Home >Backend Development >Golang >How to Call Functions in Static Object Files from Go?
Calling Functions in Static Object Files from Go
You seek to invoke functions from a shared library (.so) file within Go. While you may have encountered suggestions to employ syscall.LoadLibrary for this purpose, your attempts have been met with the error "undefined: syscall.LoadLibrary."
However, it is indeed feasible to load a shared library and access its functions from Go. To achieve this on a POSIX platform, you can leverage cgo and interact with the system's native API.
Here's a simple demonstration using cgo:
<code class="go">// +build linux darwin // #cgo LDFLAGS: -ldl // #include <dlfcn.h> package main import ( "C" "fmt" ) func foo() { // Load the shared library handle := C.dlopen(C.CString("libfoo.so"), C.RTLD_LAZY) // Retrieve the function pointer from the library bar := C.dlsym(handle, C.CString("bar")) // Print the function pointer address fmt.Printf("bar is at %p\n", bar) } func main() { foo() }</code>
In this example:
Note that the exact syntax and function names may vary depending on your underlying system and compiler. By utilizing cgo and interacting with the native system API, you can bridge the gap between Go and shared libraries, extending the capabilities of your applications.
The above is the detailed content of How to Call Functions in Static Object Files from Go?. For more information, please follow other related articles on the PHP Chinese website!