Below is a working example in C. Once you have
that going, then add the CGO layer on top to call from Go.
Note I seem to recall you might have to mark your C function as //extern ...maybe, if
in a separate C file and not inline in the .go file... read the CGO docs
in full for details.
$ cat libexample.c
#include <stdio.h>
int multiply(int a, int b) {
return a * b;
}
$ gcc -shared -o libexample.so -fPIC libexample.c
$ cat dynamic_loading.c
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
int main() {
// Open the shared library
void* handle = dlopen("./libexample.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "Error loading library: %s\n", dlerror());
return 1;
}
// Get the function pointer by name
int (*multiply)(int, int) = dlsym(handle, "multiply");
if (!multiply) {
fprintf(stderr, "Error finding function: %s\n", dlerror());
dlclose(handle);
return 1;
}
// Call the function
int result = multiply(5, 7);
printf("5 * 7 = %d\n", result);
// Clean up
dlclose(handle);
return 0;
}
$ gcc -o user_of_library dynamic_loading.c
$ ./user_of_library
5 * 7 = 35
Go host, from AI but does run
package main
/*
#cgo LDFLAGS: -ldl
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
// Define the function type that matches our C function
typedef int (*multiply_func)(int, int);
// Helper function to load and call the multiply function
int call_multiply(int a, int b) {
void* handle = dlopen("./libexample.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "Error loading library: %s\n", dlerror());
return -1;
}
// not C, but you'll need the moral equivalent of
// defer dlclose(handle);
// to clean up.
multiply_func multiply = (multiply_func)dlsym(handle, "multiply");
if (!multiply) {
fprintf(stderr, "Error finding function: %s\n", dlerror());
return -1;
}
return multiply(a, b);
}
*/
import "C"
import "fmt"
func main() {
// Call the C function through our wrapper
result := C.call_multiply(C.int(5), C.int(7))
if result == -1 {
fmt.Println("Error calling multiply function")
return
}
fmt.Printf("5 * 7 = %d\n", int(result))
}
$ go run user_of_lib_from_go.go
5 * 7 = 35