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

Related :   Bitbake / Yocto recipes for cross compiling golang program

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 https://lynxbee.com/how-to-resolve-error-no-buildable-go-source-files-in/ and add CGO_ENABLED=1 before go build.


lynxbee_ezoic

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


Leave a Comment

Android Android Applications Android Build system Android Commands Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded