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 native imports.

Wrapping C code

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 Go packages from Python

Now your C code is accessible from a Go package. Grumpy allows you to import and use Go packages from Python, so we can use this capability to (indirectly) run C code you wrapped:

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