Skip to content

Instantly share code, notes, and snippets.

@gcatlin
Created July 13, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcatlin/e09359f6e53f37e74a82 to your computer and use it in GitHub Desktop.
Save gcatlin/e09359f6e53f37e74a82 to your computer and use it in GitHub Desktop.
Dynamic loading/unloading of Go shared library
#!/bin/sh
go build -buildmode=c-shared lib.go
clang main.m -g -Wall -Werror -Wfatal-errors -pedantic -Wno-c11-extensions -Wno-unused-variable -Wno-unused-function -o main.out
package main
import "C"
import "fmt"
//export foo
func foo(a, b int) int {
fmt.Println("lib.foo():", a+b)
return a + b
}
func main() {}
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dlfcn.h>
typedef int (*foo_fn)();
int mtime(char *fileName) {
struct stat fileStat;
if (stat(fileName, &fileStat) == 0) {
return fileStat.st_mtimespec.tv_sec;
}
return 0;
}
int main(int argc, const char* argv[])
{
foo_fn foo;
void *handle;
int lastWrite = 0;
while (true) {
if (mtime("lib") > lastWrite) {
dlclose(handle);
lastWrite = mtime("lib");
handle = dlopen ("lib", RTLD_LAZY);
*(void**)(&foo) = dlsym(handle, "foo");
}
printf("%d\n", foo(1, 2));
sleep(1);
}
dlclose(handle);
}
@geraldstanje
Copy link

hi, does -buildmode=c-archive work?

@networkimprov
Copy link

My goal is to be able to make changes to a running Go game engine without needing to completely reload the game.

Did you go ahead with this idea, and if so, is any part of the code open source?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment