英文:
problems when accessing C union field
问题
我想在Go中访问C联合体的字段。以下是我的源代码,但是在编译时出现错误:
package main
// #include <stdio.h>
// #include <stdlib.h>
// union bar {
// char c;
// int i;
// double d;
// };
import "C"
import "fmt"
func main() {
var b *C.union_bar = new(C.union_bar)
b.c = 4
fmt.Println(b)
}
当我构建时,我得到以下错误:
b.c未定义(类型*[8]byte没有字段或方法c)
谁能告诉我正确的访问联合字段的方法?
英文:
I'd like to access the field of C union in Go. below is my source code, but i got an error when compile it:
package main
// #include <stdio.h>
// #include <stdlib.h>
// union bar {
// char c;
// int i;
// double d;
// };
import "C"
import "fmt"
func main() {
var b *C.union_bar = new(C.union_bar)
b.c = 4
fmt.Println(b)
}
when i build, i got errors like below:
b.c undefined (type *[8]byte has no field or method c)
Who could tell me the correct approach to access a union field?
答案1
得分: 5
似乎为了类型安全起见,联合被视为[N]byte,其中N是最大联合项的大小。因此,在这种情况下,需要将“Go可见”类型处理为[8]byte。然后它似乎可以工作:
package main
/*
#include <stdio.h>
#include <stdlib.h>
union bar {
char c;
int i;
double d;
} bar;
void foo(union bar *b) {
printf("%i\n", b->i);
};
*/
import "C"
import "fmt"
func main() {
b := new(C.union_bar)
b[0] = 1
b[1] = 2
C.foo(b)
fmt.Println(b)
}
注意:在具有其他字节顺序的机器上,相同的代码将打印不同的数字。
英文:
Seems like unions are treated, for type safety, as [N]byte, N == size of the biggest union item. Thus it is necessary to handle the "Go visible" type as [8]byte in this case. Then it appears to work:
package main
/*
#include <stdio.h>
#include <stdlib.h>
union bar {
char c;
int i;
double d;
} bar;
void foo(union bar *b) {
printf("%i\n", b->i);
};
*/
import "C"
import "fmt"
func main() {
b := new(C.union_bar)
b[0] = 1
b[1] = 2
C.foo(b)
fmt.Println(b)
}
(11:28) jnml@celsius:~/src/tmp/union$ go build && ./union
513
&[1 2 0 0 0 0 0 0]
(11:28) jnml@celsius:~/src/tmp/union$
Note: The same code would print a different number at a machine with other endianness.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论