After compiling libadd.go (with the command: "go build -buildmode=c-shared -o libadd.so libadd.go", it will have created 2 files (a libadd.so and libadd.h), the libadd.so is the shared library to call from python as shown in call_lib.h
Last active
June 21, 2018 01:11
-
-
Save p4tin/3e90aae182a14e66590a647fcdfa2ccf to your computer and use it in GitHub Desktop.
Calling GO from python
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
# python call_lib.py | |
from ctypes import cdll | |
lib = cdll.LoadLibrary('./libadd.so') | |
print "Loaded go generated SO library" | |
result = lib.add(2, 3) | |
print result | |
lib.longRun() |
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
//libadd.go | |
// - go build -buildmode=c-shared -o libadd.so libadd.go | |
package main | |
import ( | |
"C" | |
"sync" | |
"fmt" | |
"time" | |
"math/rand" | |
) | |
var wg sync.WaitGroup | |
//export add | |
func add(left, right int) int { | |
return left + right | |
} | |
//export longRun | |
func longRun() { | |
wg.Add(15) | |
rand.Seed(time.Now().UTC().UnixNano()) | |
for i:=1;i<16;i++ { | |
go waitTime(i, rand.Int63n(5)) | |
} | |
wg.Wait() | |
} | |
func waitTime(i int, t int64) { | |
defer wg.Done() | |
time.Sleep(time.Duration(t) * time.Second) | |
fmt.Println("Completed Thread:", i) | |
} | |
func main() { | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment