Skip to content
This repository has been archived by the owner on Mar 23, 2023. It is now read-only.

Using C libraries from Python

Dylan Trotter edited this page Jun 1, 2017 · 8 revisions

Although using CPython extension modules is not supported by Grumpy, it is still possible to use C libraries. In a nutshell, this is done by wrapping the C library using cgo, and then using the Go package from Python via Grumpy native imports.

Wrap your C library

Using cgo is discussed extensively elsewhere so I won't go into too many details. First, create a file called build/src/cmath/cmath.go (all files and commands will be relative to the Grumpy source tree) containing the following code:

package cmath

/*
#include <math.h>
*/
import "C"

func Sqrt(x float64) float64 {
	return float64(C.sqrt(C.double(x)))
}

Build the package using the build subdirectory as your GOPATH:

GOPATH=$PWD/build go build cmath

Import the Go package from Python

Now your C code is accessible from a Go package. Grumpy allows you to import and use Go packages from Python using the native import mechanism, so we can (indirectly) call the C function you wrapped:

$ echo "from __go__.cmath import Sqrt; print Sqrt(81)" | make run
9.0

Gotchas

Since C and Go have very different memory management strategies, it's very easy to cause problems by passing Go pointers into C and vice versa. It's important to be aware of where pointers end up. For more details, see the cgo command docs.