Skip to content

Instantly share code, notes, and snippets.

@dbalan
Created March 29, 2015 05:51
Show Gist options
  • Save dbalan/ace29f0c43638ee4f81d to your computer and use it in GitHub Desktop.
Save dbalan/ace29f0c43638ee4f81d to your computer and use it in GitHub Desktop.
cgo sample code
#include "add.h"
int add_two_numbers(int x, int y) {
return x + y;
}
int add_fzed_two_numbers(int x, int y) {
return add_two_numbers(FuzzNumber(x),
FuzzNumber(y));
}
struct hello return_person(void) {
struct hello p;
return p;
}
union quantity return_quantity(void) {
union quantity q;
q.weight = 3.14;
return q;
}
/* adds two numbers */
int add_two_numbers(int, int);
/* export to go */
int add_fzed_two_numbers(int, int);
struct hello return_person(void);
union quantity return_quantity(void);
/* importing from go is also possible */
extern int FuzzNumber(int);
struct hello
{
int age;
};
union quantity {
float weight;
int count;
};
// +build linux,cgo darwin,cgo
package main
import (
"fmt"
"unsafe"
)
/*
#include "add.h"
*/
import "C"
//export FuzzNumber
func FuzzNumber(i int32) int32 {
return i + 1
}
func main() {
fmt.Printf("Return from c func: %d\n", C.add_fzed_two_numbers(2, 4))
// func returning c struct
p := C.return_person()
p.age = 12
// declare and use
var param C.struct_hello
param.age = 12
fmt.Print("Struct repr: ")
fmt.Println(param)
// func returing union
q := C.return_quantity()
fmt.Print("Union repr: ")
fmt.Println(q)
ptr := (*float32)(unsafe.Pointer(&q))
*ptr = 3.14
// declare a union
var uparam C.union_quantity
uptr := (*int32)(unsafe.Pointer(&uparam))
fmt.Print("pointer to union: ")
fmt.Println(uptr)
*uptr = 2
fmt.Println(*uptr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment