Home  >  Article  >  Backend Development  >  How to Call Functions from Shared Object Files in Go?

How to Call Functions from Shared Object Files in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 13:51:30685browse

How to Call Functions from Shared Object Files in Go?

Calling Functions from Shared Object Files in Go

It's possible to call functions from static object (.so) files within Go programs. Contrary to the popular claim, the syscall.LoadLibrary function doesn't exist in the Go standard library. Instead, on POSIX platforms, you can leverage cgo to utilize the functions dlopen and friends.

Here's an example code snippet that illustrates how to achieve this:

<code class="go">
// #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)
}
</code>

By using cgo and the appropriate system calls, you can load a shared object library and invoke its exported functions from within your Go program.

The above is the detailed content of How to Call Functions from Shared Object Files in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn