cgo **char to slice string 将C语言的**char转换为切片字符串

huangapple go评论67阅读模式
英文:

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 &quot;C&quot;
import &quot;unsafe&quot;

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

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

huangapple
  • 本文由 发表于 2016年3月24日 05:03:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/36188649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定