c++gocgogo-map

How to use GoMap in Cgo?


I'm trying to call Go from c++. My code operates on maps, and I can't seem to make maps work with cgo.

main.go:

package main

import (
    "C"
    "fmt"
)

func main() {}

//export PrintMap
func PrintMap(m map[string]string) {
    fmt.Println(m)
}

Which "compiles" to main.h:

typedef void *GoMap;

extern void PrintMap(GoMap p0);

How can I successfully create a GoMap in my c++ code and pass it to the go code?


Solution

  • You can't. In fact, you can't really do anything with this type with cgo due to the pointer-passing rules that allow cgo to work safely with Go's concurrency and garbage collector. Maps are on the list of types that "always include Go pointers", and therefore maps can't be passed as arguments to C functions, returned from Go functions that are called by C code, or stored by C.

    It's hard to give a recommendation on what you should do without seeing more of what you're trying to accomplish, but the usual workaround for this is to have the Go code hold objects in a map, and pass the C code a key from that map (as e.g. a C string or int, which can be passed or stored freely) as a handle to the object contained within. C then does all of its interaction with the objects through Go functions, which can use the key to find the correct value in the map. A slice would work too.