Skip to content

Instantly share code, notes, and snippets.

@zealws
Last active October 24, 2021 00:09
Show Gist options
  • Save zealws/42f0fab158d2c24af602b5f9b02923bd to your computer and use it in GitHub Desktop.
Save zealws/42f0fab158d2c24af602b5f9b02923bd to your computer and use it in GitHub Desktop.
Calling a Go function from Python
package main
// this example prepared with go version go1.17.1 linux/amd64
import (
"C"
"fmt"
)
//export Greet
func Greet(c_target *C.char) *C.char {
target := C.GoString(c_target)
greeting := fmt.Sprintf("Hello, %s!", target)
return C.CString(greeting)
}
func main() {}
#!/usr/bin/env python3
from ctypes import cdll, c_char_p
import sys
target: str = "world"
if len(sys.argv) > 1:
target = sys.argv[1]
real_target: c_char_p = c_char_p(target.encode())
lib = cdll.LoadLibrary("./libgreet.so")
lib.Greet.argtypes = [c_char_p]
lib.Greet.restype = c_char_p
greeting: bytes = lib.Greet(real_target)
print(greeting.decode())
libgreet.so: greet.go
go build -o libgreet.so -buildmode=c-shared greet.go
# ./main.py
Hello, world!
# ./main.py zealws
Hello, zealws!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment