Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call linux shared library functions in Go?

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 ?

like image 784
Agniva De Sarker Avatar asked Jun 10 '14 19:06

Agniva De Sarker


People also ask

How does Linux find shared libraries?

Therefore, Linux systems use the /etc/ld. so. cache configuration file, which caches a list of all shared libraries and their location in the system.

How do you call a function in a library?

To call a function in function library, you specify the library and function name. For an example of how to call functions in a library that uses JavaScript, refer to the example in the Load function, see Load. For IPL, use the following example which uses the following format: function_library.

How do I access libraries in Linux?

By default, libraries are located in /usr/local/lib, /usr/local/lib64, /usr/lib and /usr/lib64; system startup libraries are in /lib and /lib64. Programmers can, however, install libraries in custom locations. The library path can be defined in /etc/ld. so.

Where are library files stored in Linux?

The library file is copied to a standard directory so that client programs, without fuss, can access the library. A typical location for the library, whether static or dynamic, is /usr/lib or /usr/local/lib ; other locations are possible.


1 Answers

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.

like image 118
fuz Avatar answered Sep 23 '22 17:09

fuz