CGO 中的 golang 结构体与 C 结构体

bpl*_*bpl 5 go cgo

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

    //...
}
Run Code Online (Sandbox Code Playgroud)

Sea*_*ays 7

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

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)
}
Run Code Online (Sandbox Code Playgroud)

输出

{Point:{x:1 y:2}}
Run Code Online (Sandbox Code Playgroud)