Skip to content

Instantly share code, notes, and snippets.

@zelenko
Forked from tejainece/cgo1.go
Created August 11, 2018 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zelenko/09ad9b7d8255157122953b612fa2ce25 to your computer and use it in GitHub Desktop.
Save zelenko/09ad9b7d8255157122953b612fa2ce25 to your computer and use it in GitHub Desktop.
Examples of calling C code from Golang
package main
//#include<stdio.h>
//void inC() {
// printf("I am in C code now!\n");
//}
import "C"
import "fmt"
func main() {
fmt.Println("I am in Go code now!")
C.inC()
}
#include<stdio.h>
void inCFile() {
printf("I am in C code in a .c file now!\n");
}
package main
/*
extern void inCFile();
*/
import "C"
import "fmt"
func main() {
fmt.Println("I am in Go code now!")
C.inCFile()
}
#include<stdio.h>
#include "_cgo_export.h"
void inCFile() {
printf("I am in C code in a .c file now!\n");
callFromC();
}
package main
/*
#include<stdio.h>
extern void inCFile();
*/
import "C"
import "fmt"
func main() {
fmt.Println("I am in Go code now!")
C.inCFile()
}
//export callFromC
func callFromC() {
fmt.Println("I am in Go code but I was called from C!")
}
#include<stdio.h>
#include "_cgo_export.h"
char * inCFile(char *str) {
char *ret = "C String";
printf("Received string from Go: %s\n", str);
return ret;
}
package main
/*
#include<stdio.h>
#include <stdlib.h>
extern char * inCFile(char *str);
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
cstr := C.CString("Go string!")
defer C.free(unsafe.Pointer(cstr))
cString := C.inCFile(cstr)
gostr := C.GoString(cString)
fmt.Println("Received string from C: " + gostr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment