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 Build system Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media 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 / Ask Question