cgo ** char to slice string

时间:2016-03-23 21:04:00

标签: go cgo

我使用cgo开发了一个pam模块。 无法转换为[]字符串a ** char

func pam_sm_authenticate(pamh *C.pam_handle_t, flags C.int, argc C.int, argv **C.char) int { fmt.Println(C.GoString(*argv[0])) return 0 }

错误是

invalid operation: argv[0] (type **C.char does not support indexing)

如果您知道,请告诉我。

1 个答案:

答案 0 :(得分:1)

从cgo wiki拼凑起来:https://github.com/golang/go/wiki/cgo#Turning_C_arrays_into_Go_slices

import "C"
import "unsafe"

func GoStrings(argc C.int, argv **C.char) []string {

    length := int(argc)
    tmpslice := (*[1 << 30]*C.char)(unsafe.Pointer(argv))[:length:length]
    gostrings := make([]string, length)
    for i, s := range tmpslice {
        gostrings[i] = C.GoString(s)
    }
    return gostrings
}