5

I will use cgo to wrap one c library as go library for the project usage. I read the document, it seems there are lots of rules while using cgo. I don't know whether this is legal or not.

Both LibCtx and Client is a struct in C. Is this a legal way to put C struct into a golang struct?

//DBClientLib.go

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

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

    //...
}
bpl
  • 51
  • 1
  • 2

1 Answers1

7

Yes, this is totally legal. Check out this short example:

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

OUTPUT

{Point:{x:1 y:2}}
Seaskyways
  • 3,630
  • 3
  • 26
  • 43
  • 1
    Anyone know how to work when pass C reference struct to another C function C.myfunc(struct Point *p) ? e.g. C.myfunc(&point.Point), I get no compile error but "cgo argument has Go pointer to Go pointer" – kiwi Feb 25 '22 at 09:27