Skip to content

Instantly share code, notes, and snippets.

@cavaliercoder
Last active May 4, 2016 16: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 cavaliercoder/688a3cd7dac20c8edb0c0f6f2851b54d to your computer and use it in GitHub Desktop.
Save cavaliercoder/688a3cd7dac20c8edb0c0f6f2851b54d to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
#include <errno.h>
typedef void (*golib_func)(void);
int main() {
void *golib = NULL;
golib_func f;
pid_t child = -1;
// load lib and func symbol
if (NULL != (golib = dlopen("golib.dylib", RTLD_NOW))) {
if (NULL != (f = dlsym(golib, "TestNetDial"))) {
printf("Calling from parent:\n");
(*f)();
// fork
if (0 < (child = fork())) {
waitpid(child, NULL, 0);
dlclose(golib);
} else if (0 == child) {
// call golib from child pid
printf("Calling from child:\n");
(*f)();
exit(0);
} else {
printf("failed fork: 0x%0X\n", errno);
}
} else {
printf("%s\n", dlerror());
}
} else {
printf("%s\n", dlerror());
}
}
package main
import "C"
import (
"fmt"
"net"
)
func main() {
// nothing to do here
}
//export TestNetDial
func TestNetDial() {
conn, err := net.Dial("tcp", "golang.org:443")
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Printf("--> Connected to %s\n", conn.RemoteAddr())
}
all: cbin golib.dylib
cbin: cbin.c
gcc -o cbin cbin.c
golib.dylib: golib.go
go build -buildmode=c-shared -o golib.dylib golib.go
clean:
rm -vf cbin golib.dylib
.PHONY: all clean
@cavaliercoder
Copy link
Author

FYI Makefile targets OS X. replace s/dylib/so/g for Linux.

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