【问题标题】:golang struct with C struct in CGOCGO中带有C结构的golang结构
【发布时间】:2019-06-03 16:33:40
【问题描述】:

我将使用 cgo 将一个 c 库包装为 go 库以供项目使用。我阅读了文档,使用 cgo 时似乎有很多规则。我不知道这是否合法。

LibCtx 和 Client 都是 C 中的结构。这是将 C 结构放入 golang 结构的合法方式吗?

//DBClientLib.go

type DBClient struct {
    Libctx C.LibCtx
    LibClient C.Client
}

func (client DBClient) GetEntry(key string) interface{} {

    //...
}

【问题讨论】:

    标签: go cgo


    【解决方案1】:

    是的,这是完全合法的。看看这个简短的例子:

    package main
    
    /*
    typedef struct Point {
        int x , y;
    } Point;
    */
    import "C"
    import "fmt"
    
    type CPoint struct {
        Point C.Point
    }
    
    func main() {
        point := CPoint{Point: C.Point{x: 1, y: 2}}
        fmt.Printf("%+v", point)
    }
    

    输出

    {Point:{x:1 y:2}}
    

    【讨论】:

      猜你喜欢
      • 2013-09-22
      • 2021-11-15
      • 2018-09-08
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多