Skip to content

Instantly share code, notes, and snippets.

@Mumakil
Last active May 11, 2016 05:51
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 Mumakil/3b19e48bbd8af834edacf6f2ac4a0776 to your computer and use it in GitHub Desktop.
Save Mumakil/3b19e48bbd8af834edacf6f2ac4a0776 to your computer and use it in GitHub Desktop.
Helsinki Gophers May 2016 meetup Cgo code examples
package main
// #import <stdio.h>
// #import <stdlib.h>
import "C"
import "unsafe"
// AllocateAndFree allocates a C string, prints it and frees it
func AllocateAndFree() {
cStr := C.CString("I'm a string, yay!")
defer C.free(unsafe.Pointer(cStr))
C.puts(cStr)
}
#include <stdio.h>
#include "hello_world.h"
void hello_world() {
printf("Hello world!\n");
}
package main
// #include "hello_world.h"
import "C"
// HelloWorld prints out hello world using C code
func HelloWorld() {
C.hello_world()
// Prints "Hello world!"
}
void hello_world();
package main
import (
"fmt"
)
func main() {
fmt.Println("Example 1: hello world using C")
HelloWorld()
fmt.Println("Example 2: call C namespace")
PrintSquared(8)
fmt.Println("Example 3: allocate and free")
AllocateAndFree()
}
package main
// #include <math.h>
import "C"
import "fmt"
// PrintSquared squares the number using C math
func PrintSquared(f float64) {
n, _ := C.pow(C.double(f), C.double(2))
fmt.Printf("%f squared is %f\n", f, float64(n))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment