Libyang and Golang


Cgo lets Go packages call C code. Given a Go source file written with some special features, cgo outputs Go and C files that can be combined into a single Go package.

A good resource on this can be found at here.

Building libyang

You can simply install locally libyang with executing the following steps.

$ git clone
$ cd libyang
$ mkdir build; cd build
$ cmake ..
$ make
# make install

If you want to create a static libyang binary too, add "-DSTATIC=true" to cmake.

$ cmake -DSTATIC=true ..

Include libyang into your project

To use the libyang library in your go project add these lines of code under your import statement.

#cgo LDFLAGS: -lyang
#include <libyang/libyang.h>
import "C"

For a static build also add pcre or you will get errors.

#cgo LDFLAGS: -lpcre

Compile your code

To create a binary that is dynamically linked to libyang simply run:

go build

For a static build execute "go build" with additional flags:

go build --ldflags '-extldflags "-static"'

String handling

It is common to pass strings between Golang and C, for that there are functions.

//Golang string to C string
text := "test"
var str *C.char
str = C.CString(text)

//C string to Golang
var str *C.char
C.lyd_print_mem(&str, node, C.LYD_XML, 0)
fmt.Printf("Generated xml from xpath:\n%s\n", C.GoString(str))

C/Go Callbacks

When you want to pass Golang callback to C it requires a bit more work. For this you need a C file and a header.

Include the header in Golang with:

// ...
#include "helper.h"
import "C"

You need to export the Golang function, you can do that with:

export golang_function
func golang_function( ...

In the file helper.c define the function and add requried header files.

#include <libyang/libyang.h>
#include "helper.h"
#include "_cgo_export.h"

C Variadic functions

Golang does not support variadic functions so you will need to create helper functions for C variadic functions.

golang (last edited 2017-03-23 11:28:05 by mnovakovic)