Last active
May 4, 2016 16:07
-
-
Save cavaliercoder/688a3cd7dac20c8edb0c0f6f2851b54d to your computer and use it in GitHub Desktop.
This file contains 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 <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()); | |
} | |
} |
This file contains 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" | |
"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()) | |
} |
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI Makefile targets OS X. replace
s/dylib/so/g
for Linux.