Search code examples
pythonpython-3.xgoshared-librariesctypes

Cannot use go shared library in my python file


I have a file called main.go which defines a function called test. I would like to be able to call this function from my python script.

main.go

package main

import "C"

// export test
func test() int {
    return 1
}

func main() {}

compiled with : go build -o lib.so -buildmode=c-shared main.go

main.py

import ctypes

mylib = ctypes.CDLL("./lib.so")


result = mylib.test()


print(result)

when i run the python program i get this error: AttributeError: ./lib.so: undefined symbol: test

What am i missing ?

Go version go version go1.21.3 linux/amd64

Python Version: Python 3.10.12

I tried updating Go (previously I had version 1.21.1)


Solution

  • Everything is correct except // export there is an extra space that creates the problem

    package main
    
    import "C"
    
    //export test      <------ remove the extra space here
    func test() int {
        return 1
    }
    
    func main() {}
    
    python main.py
    

    Output:

    1