简体   繁体   中英

Pass Go Pointer via "cgo" as a Key

I am doing some interop between Go and Python. I am planning on creating objects in the Go land and only access them from Python through Go methods. For example, struct A below will only be created and destroyed in the Go land and only be accessed through method1 . But Python code does need to know the handle/pointer to instances of struct A such that when it passes this handle/pointer to a Go function, the Go function knows to convert it to a Go pointer and calls its method. In other words, Python does not directly use the Go pointer *A as a pointer that references/dereferences memory, but rather uses it as a key to identify the Go objects.

The problem is that it is not valid to do int(a) for var a *A and I cannot directly pass *A between cgo methods.

What can I do so that I can convert *A to some blackbox key that is an integer and later convert it back to *A ?

type A struct {
    a int
}

func (a *A) method1(){
    fmt.Println("Hello world")
}

Short answer: you can't really.

Longer answer, is that because Go is garbage collected, you're able to pass pointers to C, but it must C must preserve this property: C should not store any Go pointers in Go memory, even temporarily, and may not keep a copy of a Go pointer after a call returns.

You can read a much more about the handling and uses in the cgo documentation https://golang.org/cmd/cgo/#hdr-Passing_pointers , which may help you with your usecase, maybe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM