Loading linux shared objects from go code

Saturday, January 26, 2013 » luks, robbje, spq

This describes how to load shared object files from go

Description

GO does not provide API Functions to load shared objects in linux. However, you can use cgo to call native C functions, which in turn can do the job for you:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main

/*
#cgo LDFLAGS: -ldl
#include <stdlib.h>
#include <dlfcn.h>

int dlopen_wrap(const char* file) {
    void *handle = dlopen(file, RTLD_LAZY);
    if(handle == NULL)
        return 0;
    int (*run)(void);
    *(int**) (&run) = dlsym(handle, "run");
    if(run == NULL)
        return 0;
    int result = (*run)();
    dlclose(handle);
    return result;
}

*/
import "C"
import "fmt"

func main() {
    res := C.dlopen_wrap(C.CString("./test.so"))
    fmt.Println(res);
}

Now, provided, that the shared object test.so provides extern int run(); it should call that function.