How can I call linux library functions in Go?

I have a .so file whose functions I would call Go code.

How can I do it? I read the cgo and syscall package. They are close to what I want, but I do not see a place where I can call functions in the .so file.

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

Can anyone help?

+6
source share
1 answer

If you want to use a shared library that is statically known at compile time, you can simply use cgo . Read the documentation on how to do this exactly, but usually you specify some linker flags and a couple of commented lines. The following is an example of calling the bar() function 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 dynamically loaded at runtime. You can use dlopen() , dlsym() and dlclose() to open a shared library, get the address of one of the functions inside, and finally close the library. Note that you cannot do these things in Go, you need to write shell code in C that implements the necessary logic for you.

+4
source

Source: https://habr.com/ru/post/970643/


All Articles