I try to call few shared object functions from Go. I don't want to write a C commented code to build a CGO interface for all functions.
I write my shared object like that:
#include <stdio.h>
void greet(char* name) {
printf("Hello, %s!\n", name);
}
I compile it with: gcc -shared -fPIC -o libgreet.so greet.c.
My Go code to call the greet function:
package main
// #cgo LDFLAGS: -ldl
// #include <dlfcn.h>
// #include <stdlib.h>
import "C"
import (
"unsafe"
"fmt"
)
func main() {
so_name := C.CString("./libgreet.so")
defer C.free(unsafe.Pointer(so_name))
function_name := C.CString("greet")
defer C.free(unsafe.Pointer(function_name))
library := C.dlopen(so_name, C.RTLD_LAZY)
defer C.dlclose(library)
function := C.dlsym(library, function_name)
greet := (*func(*C.char))(unsafe.Pointer(&function))
fmt.Println("%p %p %p %p\n", greet, function, unsafe.Pointer(function), unsafe.Pointer(&function))
(*greet)(C.CString("Bob"))
}
When i start the executable i get SIGSEGV errors.
I try to debug it with gdb and pointers printed seems to be good (that the same value than x greet in gdb). The segmentation fault come on the instruction 0x47dde4 <main.main+548> call r8 where $r8 contains 0x10ec8348e5894855 (probably not a memory address).
Do you have any idea how i can fix this error ? There is a soluce to call shared object function in Go without a C code commented as the CGO syntax (i don't find any documentation to do it) ?