Skip to content

Instantly share code, notes, and snippets.

@owen800q
Last active September 16, 2019 05:12
Show Gist options
  • Select an option

  • Save owen800q/0522e4d6c5d884ed5aa02dc03209bbad to your computer and use it in GitHub Desktop.

Select an option

Save owen800q/0522e4d6c5d884ed5aa02dc03209bbad to your computer and use it in GitHub Desktop.
Call go functions in Python

Method 1:

Using socket, build go as a server. From python, pass parameter over socket connection and get results from go server.

Method 2:

Compile Go to shared object library, call from python with ctypes

sample code

libnative.go

package main

import "C"
import "fmt"

//export Sum
func Sum(a int, b int) int {
    return a + b
}

//export GetName
func GetName(firstName string) string{
    return fmt.Sprint(firstName,"-so")
}

func main(){

}

Note that even to compile into a dynamic library, must have a main function. must have 'import C' statement and the comment export function name must be annotated above the function signature

run

go build -buildmode=c-shared -o libnative.so ./libnative.go

result

-rw-r--r--  1 xxx xxx 1M Sep 16 12:48 libnative.h
-rw-r--r--  1 xxx xxx 3M Sep 16 12:48 libnative.so
-rw-r--r--  1 xxx xxx 1M Sep 16 12:47 native.go

callnative.py

import ctypes
lib = ctypes.CDLL('./libnative.so')
a = lib.Sum(2,3)
print(a)
>>> 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment