build an extension in go

To build an extension in Go, you need to create a new Go package, and then compile it into a shared library that can be loaded from other programming languages. Here are the basic steps:

  1. Create a new Go package that defines the functions you want to export. For example:
main.go
package myextension

//export MyFunction
func MyFunction() {
  // implementation here
}
88 chars
7 lines

Note the "//export" comment before the function definition. This tells the Go compiler to export the function for use in other languages.

  1. Build the package with the "buildmode=c-shared" flag to compile it into a shared library:
main.go
go build -o myextension.so -buildmode=c-shared myextension.go
62 chars
2 lines

This will create a shared library called "myextension.so" that contains your exported functions.

  1. Load the shared library from another programming language. For example, in Python, you can use the "ctypes" library to load the shared library and call its exported functions:
main.go
import ctypes

myextension = ctypes.cdll.LoadLibrary('./myextension.so')

myextension.MyFunction()
99 chars
6 lines

Note that the function name in Python matches the exported function name in Go (without the "//export" comment).

That's it! You should now be able to build and use your Go extension in other programming languages.

gistlibby LogSnag