duan89197 2012-09-25 08:41
浏览 39
已采纳

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条回答 默认 最新

  • dongxinyue2817 2012-09-25 09:33
    关注

    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
    ", 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)