V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
eloah
V2EX  ›  Go 编程语言

Golang 对于 C 结构体中的一个问题

  •  
  •   eloah · 2018-03-21 15:54:29 +08:00 · 1834 次点击
    这是一个创建于 2199 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有以下一个 C 的结构体

    #pragma pack(1) //单字节对齐
    typedef struct{
    	unsigned char	a[2048];
    	unsigned int	b;
    }sampleStruct;
    #pragma pack()
    

    在 Golang 中给这个结构体赋值

    var sampleStruct C.sampleStruct = C.sampleStruct{
    	[2048]C.uchar{}
    	C.uint(0)
    }
    

    理论上应该是成功的,但是编译器却提示我

    cannot use _Ctype_uint(0) (type _Ctype_uint) as type [4]byte in field value

    测试平台

    • macOS 10.12.6 golang 1.10
    • ubuntu 16.04.04 64bit LTS golang 1.8.3

    有大佬知道为什么会这样吗

    另外,定义如下函数

    unsigned int add(unsigned int a, unsigned int b) {
        return a + b;
    }
    

    在 golang 中使用如下调用

    C.add(C.uint(2), C.uint(1))
    

    是成功的

    第 1 条附言  ·  2018-03-21 16:50:48 +08:00
    package main

    /*
    #cgo CFLAGS: -O2
    typedef struct{
    unsigned char a[2049];
    unsigned int c;
    }sStatisticsPhishingData;
    */
    import "C"
    import "fmt"

    func main() {
    var sStatisticsPhishingData C.sStatisticsPhishingData = C.sStatisticsPhishingData{
    [2049]C.uchar{},
    C.uint(0),
    }
    fmt.Println(sStatisticsPhishingData)
    }

    正确的(错误的)示例,感觉是内存对齐之类的关系......
    第 2 条附言  ·  2018-03-21 17:21:35 +08:00
    2 条回复    2018-03-21 17:20:54 +08:00
    eloah
        1
    eloah  
    OP
       2018-03-21 16:30:12 +08:00
    额......我给的这个去除了业务逻辑的代码是可以运行的......除了小的语法错误......
    我再看看......
    eloah
        2
    eloah  
    OP
       2018-03-21 17:20:54 +08:00
    因为 Golang 和 C 的对齐方式差异,可能出现这类问题
    https://github.com/Shopify/sysv_mq/issues/10
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1224 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:08 · PVG 02:08 · LAX 11:08 · JFK 14:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.