How to execute C code from go – c to golang binding

package main

// If a Go source file imports “C”, it is using cgo. The Go file will have access to anything appearing in the comment immediately preceding the line import “C”, and will be linked against all other cgo comments in other Go files, and all C files included in the build process.

/*
#include stdio.h
#include stdlib.h

void myprint(char* s) {
printf("This is in C code : %s\n", s);
}
*/
import "C"

note here: there should be no new line between closing comment (*/) and import “C” lines, like below

*/
new line
import "C"

this will result in error,
# command-line-arguments
could not determine kind of name for C.free
could not determine kind of name for C.myprint

import "unsafe"

func Example() {
cs := C.CString("This is passed from Go Code\n")
C.myprint(cs)
C.free(unsafe.Pointer(cs))
}

func main() {
Example()
}

//reference : https://github.com/golang/go/wiki/cgo

The complete source code for “main.go” is like below,

package main
/*
#include stdio.h
#include stdlib.h

void myprint(char* s) {
    printf("This is in C code : %s\n", s);
}
*/
import "C"

import "unsafe"

func Example() {
    cs := C.CString("This is passed from Go Code\n")
    C.myprint(cs)
    C.free(unsafe.Pointer(cs))
}

func main() {
	Example()
}

Compile the code as,

go build

If you are cross compiling same code, you can refer to post http://www.lynxbee.com/how-to-resolve-error-no-buildable-go-source-files-in/ and add CGO_ENABLED=1 before go build.

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded
Tags: ,

Leave a Reply