-
Notifications
You must be signed in to change notification settings - Fork 646
Using C libraries from Python
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.
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
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
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.