普通网友 2014-08-09 09:31
浏览 144

Golang:使用CGo导出C字段以使其在外部可见

Background: I'm trying to make a package that essentially provides thin Go wrappers around a C library that I'm using. The package is intentionally very raw, since several other packages depend on the low level functionalities of the C library and I don't want to copy-pasta a bunch of Go wrapper code.

Suppose I have a C-struct that looks like:

typedef struct {
    uint32_t fizz;
    uint64_t buzz;
} test

And in CGo, I wrap the C-struct and create new methods as follows:

package test    

type Test C.test

func NewTest() *Test {
    return &Test{1,2}
}

The problem is that outside of the package, I can't access the fields in the C-struct

package main

import "test"

func main() {
    t := test.NewTest()
    _ = t.fizz // ERROR!!! Unexported field name!!
}

Is there any easy way around this (other than create accessor methods for every field)?

  • 写回答

1条回答 默认 最新

  • dongpi0658 2014-08-13 14:36
    关注

    Yes, you can export C structs. But you'll need to follow the same rules for exporting a C struct as you would a Golang struct. http://golang.org/ref/spec#Exported_identifiers

    main.go

    package main
    
    import "test"
    
    func main() {
        t := test.NewTest()
        println(t.Fizz)
    }
    

    test/test.go

    package test
    
    /*
       #include "test.h"
    */
    import "C"
    
    type Test C.test
    
    func NewTest() *Test {
        return &Test{Fizz: 1, Buzz: 2}
    }
    

    test/test.h

    #include <stdint.h>
    
    typedef struct {
        uint32_t Fizz;   // notice that the first character is upper case
        uint64_t Buzz;
    } test;
    

    If for whatever reason you are unable to modify the field names in the C struct, then you will need to create a new C struct that matches the exact layout, but with the Uppercase identifiers.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么