Skip to content

Instantly share code, notes, and snippets.

@p4tin
Last active June 21, 2018 01:11
Show Gist options
  • Save p4tin/3e90aae182a14e66590a647fcdfa2ccf to your computer and use it in GitHub Desktop.
Save p4tin/3e90aae182a14e66590a647fcdfa2ccf to your computer and use it in GitHub Desktop.
Calling GO from python

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

# 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()
//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