"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Call Linux Shared Library Functions in Go?

How to Call Linux Shared Library Functions in Go?

Published on 2024-11-08
Browse:537

How to Call Linux Shared Library Functions in Go?

Calling Linux Shared Library Functions in Go

In this question, a developer seeks assistance in calling functions from a shared object (.so) file within their Go code. The ctypes package in Python, which enables access to C functions, serves as the desired functionality.

Using cgo for Static Shared Library Loading

To call functions in a statically known shared library at compile time, one can employ the cgo package. Here's an example for accessing the bar() function from libfoo.so:

package example

// #cgo LDFLAGS: -lfoo
//

#include 

import "C"

func main() {
    C.bar()
}

Dynamic Shared Library Loading with cgo

Alternatively, cgo can facilitate access to shared objects dynamically loaded at runtime. One needs to utilize the functions dlopen(), dlsym(), and dlclose() to open the shared library, retrieve function addresses, and close the library. However, these functions are not natively supported by Go and require a C wrapper to implement the necessary logic.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3