diff options
author | Ayke van Laethem <[email protected]> | 2019-04-11 23:14:10 +0200 |
---|---|---|
committer | Ron Evans <[email protected]> | 2019-04-17 11:56:40 +0200 |
commit | d2b3a5486c2c7c902f1f021638f327571373c381 (patch) | |
tree | 231fcbb93c0ba77a87b5fc541ccc957e870b3819 /testdata/cgo/main.go | |
parent | 536086988c1f91d3aac75d8e8e1a24f380743552 (diff) | |
download | tinygo-d2b3a5486c2c7c902f1f021638f327571373c381.tar.gz tinygo-d2b3a5486c2c7c902f1f021638f327571373c381.zip |
cgo: implement C unions
Unions are somewhat hard to implement in Go because they are not a
native type. But it is actually possible with some compiler magic.
This commit inserts a special "C union" field at the start of a struct
to indicate that it is a union. As such a field cannot be written
directly in Go, this is a useful to distinguish structs and unions.
Diffstat (limited to 'testdata/cgo/main.go')
-rw-r--r-- | testdata/cgo/main.go | 25 |
1 files changed, 24 insertions, 1 deletions
diff --git a/testdata/cgo/main.go b/testdata/cgo/main.go index 327d38dd9..3f1da8b6d 100644 --- a/testdata/cgo/main.go +++ b/testdata/cgo/main.go @@ -9,6 +9,10 @@ import "C" import "unsafe" +func (s C.myint) Int() int { + return int(s) +} + func main() { println("fortytwo:", C.fortytwo()) println("add:", C.add(C.int(3), 5)) @@ -36,9 +40,28 @@ func main() { println("complex float:", C.globalComplexFloat) println("complex double:", C.globalComplexDouble) println("complex long double:", C.globalComplexLongDouble) - println("struct:", C.globalStruct.s, C.globalStruct.l, C.globalStruct.f) + + // complex types + println("struct:", C.int(unsafe.Sizeof(C.globalStruct)) == C.globalStructSize, C.globalStruct.s, C.globalStruct.l, C.globalStruct.f) var _ [3]C.short = C.globalArray println("array:", C.globalArray[0], C.globalArray[1], C.globalArray[2]) + println("union:", C.int(unsafe.Sizeof(C.globalUnion)) == C.globalUnionSize) + C.unionSetShort(22) + println("union s:", C.globalUnion.s) + C.unionSetFloat(3.14) + println("union f:", C.globalUnion.f) + C.unionSetData(5, 8, 1) + println("union global data:", C.globalUnion.data[0], C.globalUnion.data[1], C.globalUnion.data[2]) + println("union field:", printUnion(C.globalUnion).f) +} + +func printUnion(union C.joined_t) C.joined_t { + println("union local data: ", union.data[0], union.data[1], union.data[2]) + union.s = -33 + println("union s method:", union.s.Int(), union.data[0] == 5) + union.f = 6.28 + println("union f:", union.f) + return union } //export mul |