Last active
October 24, 2021 00:09
-
-
Save zealws/42f0fab158d2c24af602b5f9b02923bd to your computer and use it in GitHub Desktop.
Calling a Go function 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
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() {} |
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
#!/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()) |
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
libgreet.so: greet.go | |
go build -o libgreet.so -buildmode=c-shared greet.go |
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
# ./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