A library for calling C functions from Go without Cgo.
This is beta software so expect bugs and potentially API breaking changes but each release will be tagged to avoid breaking people's code. Bug reports are encouraged.
The Ebitengine game engine was ported to use only Go on Windows. This enabled
cross-compiling to Windows from any other operating system simply by setting GOOS=windows. The purego project was
born to bring that same vision to the other platforms supported by Ebitengine.
This also means unsupported GOARCHs (freebsd/riscv64, linux/mips, etc.) will still work except for float arguments and return values.
Tier 1 platforms are the primary targets officially supported by PureGo. When a new version of PureGo is released, any critical bugs found on Tier 1 platforms are treated as release blockers. The release will be postponed until such issues are resolved.
Tier 2 platforms are supported by PureGo on a best-effort basis. Critical bugs on Tier 2 platforms do not block new PureGo releases. However, fixes contributed by external contributors are very welcome and encouraged.
* These architectures only support SyscallN and NewCallback
The example below only showcases purego use for macOS and Linux. The other platforms require special handling which can be seen in the complete example at examples/libc which supports FreeBSD and Windows.
package main
import (
"fmt"
"runtime"
"github.com/ebitengine/purego"
)
func getSystemLibrary() string {
switch runtime.GOOS {
case "darwin":
return "/usr/lib/libSystem.B.dylib"
case "linux":
return "libc.so.6"
default:
panic(fmt.Errorf("GOOS=%s is not supported", runtime.GOOS))
}
}
func main() {
libc, err := purego.Dlopen(getSystemLibrary(), purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
panic(err)
}
var puts func(string)
purego.RegisterLibFunc(&puts, libc, "puts")
puts("Calling C from Go without Cgo!")
}
Then to run: CGO_ENABLED=0 go run main.go
If you have questions about how to incorporate purego in your project or want to discuss how it works join the Discord!
Purego uses code that originates from the Go runtime. These files are under the BSD-3 License that can be found in the Go Source. This is a list of the copied files:
abi_*.h from package runtime/cgowincallback.go from package runtimezcallback_darwin_*.s from package runtimeinternal/fakecgo/abi_*.h from package runtime/cgointernal/fakecgo/asm_GOARCH.s from package runtime/cgointernal/fakecgo/callbacks.go from package runtime/cgointernal/fakecgo/go_GOOS_GOARCH.go from package runtime/cgointernal/fakecgo/iscgo.go from package runtime/cgointernal/fakecgo/setenv.go from package runtime/cgointernal/fakecgo/freebsd.go from package runtime/cgointernal/fakecgo/netbsd.go from package runtime/cgoThe files abi_*.h and internal/fakecgo/abi_*.h are the same because Bazel does not support cross-package use of
#include so we need each one once per package. (cf. issue)