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)?

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.