Skip to content

Instantly share code, notes, and snippets.

@gcatlin
Created Jul 13, 2015
Embed
What would you like to do?
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

geraldstanje commented Jul 18, 2015

hi, does -buildmode=c-archive work?

@networkimprov
Copy link

networkimprov commented Oct 14, 2015

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