访问 C 联合字段时的问题

huangapple go评论82阅读模式
英文:

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 &lt;stdio.h&gt;
// #include &lt;stdlib.h&gt;
// union bar {
//        char   c;
//        int    i;
//        double d;
// };
import &quot;C&quot;

import &quot;fmt&quot;

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 &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
union bar {
       char   c;
       int    i;
       double d;
} bar;

void foo(union bar *b) {
	printf(&quot;%i\n&quot;, b-&gt;i);
};

*/
import &quot;C&quot;

import &quot;fmt&quot;

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 &amp;&amp; ./union
513
&amp;[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.

huangapple
  • 本文由 发表于 2012年9月25日 16:41:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/12579185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定