Binary Strolls

Cyber rambling (or ranting), mostly about code

Notes on cgo

March 29, 2015 , posted in golang, c

Referencing c from go.

Basic operation

import “C” imports the C namespace into go, the comment just above this statement is treated as C.

Everything you exported from c library is available in the C namespace.

Building code is as easy as go build

Accessing standard types are easy as C.char, C.int. For complex types, prepend the type name with an underscore at end – e.g C.struct_stat.

Pointers and memory operations

Go provides an unsafe module. Go’s GC cannot manage the memory allocated in C code, you should call C.free(unsafe.Pointer) (free is defined in <stdlib.h> ensure that this library is imported) to deallocate. There are some special functions which convert Go types to C types and vice versa. (lifted from cgo documentation)

Accessing complex objects

Accessing structs from Go

You can also pass pointers

Accessing Unions : No native counterpart, instead of converting it to a type, go treats them as a block of memory represented as byte array. Accessing data is done by casting unsafe.Pointer

Extra goodies

Compiler Flags

Compiler flags can be set using the #cgo directive. (CFLAGS, LDFLAGS etc)

Restricting building

In many cases using cgo breaks the portability of your app, use build constraints to specify compatibility in source. Build constraints are comments which begin with

Now, build comment must appear before package clause and should be followed by a blank line To restrict building just to Linux with cgo,

These are evaluated as OR of each constraint so the above line becomes (linux AND cgo) OR (NOT darwin), also multiple build tags can be embedded in file.

There are other methods to restrict builds, see references.

Reference