4 ms·
According to my limited experience (small tools such as a process monitor linking to libproc) it is astonishingly easy and convenient to call C code from Go: no
by jkn 14y ago
According to my limited experience (small tools such as a process monitor linking to libproc) it is astonishingly easy and convenient to call C code from Go: no need to write bindings, as Cgo allows to access C symbols directly from Go. I would be interested in what are the difficulties when dealing with larger projects.
For illustration, here's how I call the openproc() function from libproc:
import (
/*
#cgo LDFLAGS: -lproc
#include <proc/readproc.h>
PROCTAB* my_openproc(int flags) { return openproc(flags); }
*/
"C"
)
func parse_procs() {
proc := C.my_openproc(C.PROC_FILLUSR | C.PROC_FILLCOM | C.PROC_FILLSTAT)
...
}
This illustrates one issue I found with Cgo: calling functions with variable number of arguments is not supported. I had to define a new C function "my_openproc" with a fixed number of arguments, which you can see in the metadata of the import statement. It also includes the compiler and Cgo directives that make editing a Makefile unnecessary. The code for the whole tool is contained in one Go file.