Skip to content

Commit 5da8cb0

Browse files
committed
misc/cgo: Add test for C union read/write
For #39537
1 parent 296ddf2 commit 5da8cb0

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

misc/cgo/test/cgo_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ func TestCthread(t *testing.T) { testCthread(t) }
7979
func TestEnum(t *testing.T) { testEnum(t) }
8080
func TestNamedEnum(t *testing.T) { testNamedEnum(t) }
8181
func TestCastToEnum(t *testing.T) { testCastToEnum(t) }
82+
func TestUnion(t *testing.T) { testUnion(t) }
8283
func TestErrno(t *testing.T) { testErrno(t) }
8384
func TestFpVar(t *testing.T) { testFpVar(t) }
8485
func TestHandle(t *testing.T) { testHandle(t) }

misc/cgo/test/test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,11 @@ enum E {
9595
Enum2 = 2,
9696
};
9797
98+
union U {
99+
float f32;
100+
uint64_t u64;
101+
};
102+
98103
typedef unsigned char cgo_uuid_t[20];
99104
100105
void uuid_generate(cgo_uuid_t x) {
@@ -1034,6 +1039,30 @@ func testCastToEnum(t *testing.T) {
10341039
}
10351040
}
10361041

1042+
func testUnion(t *testing.T) {
1043+
var u C.union_U
1044+
byteU := (*byte)(unsafe.Pointer(&u))
1045+
1046+
// Union U has a field whose variable type is uint64_t, so the size of this union is 8 bytes
1047+
if unsafe.Sizeof(byteU) != 8 {
1048+
t.Error("wrong union size", unsafe.Sizeof(byteU))
1049+
}
1050+
1051+
goU64 := (*uint64)(unsafe.Pointer(&u))
1052+
*goU64 = math.MaxUint64
1053+
1054+
if *goU64 != math.MaxUint64 {
1055+
t.Error("failed to assign value to union", *goU64)
1056+
}
1057+
1058+
goF32 := (*float32)(unsafe.Pointer(&u))
1059+
*goF32 = 1.0
1060+
1061+
if *goF32 != 1.0 {
1062+
t.Error("failed to assign value to union", *goF32)
1063+
}
1064+
}
1065+
10371066
func testAtol(t *testing.T) {
10381067
l := Atol("123")
10391068
if l != 123 {

0 commit comments

Comments
 (0)