Created
July 13, 2015 14:07
-
-
Save gcatlin/e09359f6e53f37e74a82 to your computer and use it in GitHub Desktop.
Dynamic loading/unloading of Go shared library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
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
hi, does -buildmode=c-archive work?