英文:
cgo **char to slice string
问题
我使用cgo开发了一个pam模块。
无法将**char转换为[]string。
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)
请告诉我你是否了解。
英文:
I have developed a pam module using the cgo.
can not be converted to []string 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
}
error is
invalid operation: argv[0] (type **C.char does not support indexing)
Please let me know if you know.
答案1
得分: 5
从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
}
英文:
Cobbled together from the 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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论