简体   繁体   中英

Go []string to C char**

I started trying to integrate some C libraries into my Go code for a project using cgo and have come across a problem.

In one of the C functions I need to pass argv to a function call. In C argv is a pointer to an array of char strings (K&R C, §5.10) and I need to convert from a slice of strings to a char**.

I have had a good look, high and low for any information on how to do variable type conversions from Go to C but there appears to be next to no documentation. Any help would be appreciated.

You'll need to create the array yourself. Something like this should do:

argv := make([]*C.char, len(args))
for i, s := range args {
    cs := C.CString(s)
    defer C.free(unsafe.Pointer(cs))
    argv[i] = cs
}
C.foo(&argv[0])

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