github.com/aykevl/tinygo@v0.5.0/testdata/cgo/main.go (about)

     1  package main
     2  
     3  /*
     4  int fortytwo(void);
     5  #include "main.h"
     6  int mul(int, int);
     7  */
     8  import "C"
     9  
    10  import "unsafe"
    11  
    12  func (s C.myint) Int() int {
    13  	return int(s)
    14  }
    15  
    16  func main() {
    17  	println("fortytwo:", C.fortytwo())
    18  	println("add:", C.add(C.int(3), 5))
    19  	var x C.myint = 3
    20  	println("myint:", x, C.myint(5))
    21  	println("myint size:", int(unsafe.Sizeof(x)))
    22  	var y C.longlong = -(1 << 40)
    23  	println("longlong:", y)
    24  	println("global:", C.global)
    25  	var ptr C.intPointer
    26  	var n C.int = 15
    27  	ptr = C.intPointer(&n)
    28  	println("15:", *ptr)
    29  	C.store(25, &n)
    30  	println("25:", *ptr)
    31  	cb := C.binop_t(C.add)
    32  	println("callback 1:", C.doCallback(20, 30, cb))
    33  	cb = C.binop_t(C.mul)
    34  	println("callback 2:", C.doCallback(20, 30, cb))
    35  
    36  	// more globals
    37  	println("bool:", C.globalBool, C.globalBool2 == true)
    38  	println("float:", C.globalFloat)
    39  	println("double:", C.globalDouble)
    40  	println("complex float:", C.globalComplexFloat)
    41  	println("complex double:", C.globalComplexDouble)
    42  	println("complex long double:", C.globalComplexLongDouble)
    43  
    44  	// complex types
    45  	println("struct:", C.int(unsafe.Sizeof(C.globalStruct)) == C.globalStructSize, C.globalStruct.s, C.globalStruct.l, C.globalStruct.f)
    46  	var _ [3]C.short = C.globalArray
    47  	println("array:", C.globalArray[0], C.globalArray[1], C.globalArray[2])
    48  	println("union:", C.int(unsafe.Sizeof(C.globalUnion)) == C.globalUnionSize)
    49  	C.unionSetShort(22)
    50  	println("union s:", C.globalUnion.s)
    51  	C.unionSetFloat(3.14)
    52  	println("union f:", C.globalUnion.f)
    53  	C.unionSetData(5, 8, 1)
    54  	println("union global data:", C.globalUnion.data[0], C.globalUnion.data[1], C.globalUnion.data[2])
    55  	println("union field:", printUnion(C.globalUnion).f)
    56  
    57  	// recursive types, test using a linked list
    58  	lastElement := &C.list_t{n: 7, next: nil}
    59  	list := &C.list_t{n: 3, next: &C.struct_list_t{n: 6, next: (*C.struct_list_t)(lastElement)}}
    60  	for list != nil {
    61  		println("n in chain:", list.n)
    62  		list = (*C.list_t)(list.next)
    63  	}
    64  }
    65  
    66  func printUnion(union C.joined_t) C.joined_t {
    67  	println("union local data: ", union.data[0], union.data[1], union.data[2])
    68  	union.s = -33
    69  	println("union s method:", union.s.Int(), union.data[0] == 5)
    70  	union.f = 6.28
    71  	println("union f:", union.f)
    72  	return union
    73  }
    74  
    75  //export mul
    76  func mul(a, b C.int) C.int {
    77  	return a * b
    78  }