hostname := C.CString("100.100.24.81")
defer C.free(unsafe.Pointer(hostname))
port := C.int(102)
struct Greetee {
const char *name;
int year;
};
g := C.struct_Greetee{
name: name,
year: year,
}
In this example we want to print something with the help of C function.
import "C"
.import "C"
line. you must comment them out. it doesn't matter that they are commented out they will work fine.// #include <stdio.h>
and // #include <stdlib.h>
4- now, all the function of the imported libraries, has added to "C" namespace. see the example to find out how it works.package main
// #include <stdio.h>
// #include <stdlib.h>
import "C"
import "unsafe"
func main() {
cs := C.CString("This is a \"Hello World\" message from C.\n")
defer func() {
C.free(unsafe.Pointer(cs))
}()
C.puts(cs)
}
$ go env -w CGO_ENABLED=1
$ go build -o ./bin/hello ./main.go
$ ./bin/hello
Note
To build the program you have to have GCC or G++ on your machine. Linux, Windows Don't forget to check add to path while installing
This is a "Hello World" message from C.