首页 > 解决方案 > CGO中带有C结构的golang结构

问题描述

我将使用 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{} {

    //...
}

标签: gocgo

解决方案


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

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}}

推荐阅读