1 回答

TA貢獻(xiàn)1828條經(jīng)驗 獲得超3個贊
1)我懷疑這cost char*是否意味著UTF16編碼。所以你所需要的只是獲取原始數(shù)據(jù):
sensigrafo := "en\000" // \000 = 0 = null termination, \0 does not valid
options := "\000"
...
uintptr(*(*unsafe.Pointer)(unsafe.Pointer(&sensigrafo))
uintptr(*(*unsafe.Pointer)(unsafe.Pointer(&options))
// *(*unsafe.Pointer) are accessing the first field of string header:
type string struct {
data *byte
len int
}
// same with slices
// but for them there's less ugly way:
sensigrafo := []byte("en\000")
options := []byte("\000")
uintptr(unsafe.Pointer(&sensigrafo[0]))
uintptr(unsafe.Pointer(&options[0]))
2) Cint和 Golangint可能有不同的 sizeof,所以這需要 cgo 聲明 ( C.int) 或手動匹配隨機(jī)選擇(如果你不想使用 cgo,也可以嘗試 int32、int64)
type senseiErr struct {
code C.int /* Golang's int32/int64 */
error_string *byte // pointer types are same as C's void* or Golang's unsafe.Pointer
}
錯誤的偏移量可能會導(dǎo)致 error_string 為空或指向隨機(jī)地址。
3)要讀取內(nèi)容,您必須使用與 C 相同的方法(讀取數(shù)據(jù)直到 null 終止字節(jié),考慮到 *byte 指向字符串的第一個元素),但我建議使用已經(jīng)實現(xiàn)的運行時函數(shù):
//go:linkname gostringn runtime.gostringn
func gostringn(p *byte, l int) string
//go:linkname findnull runtime.findnull
//go:nosplit
func findnull(s *byte) int
...
error_string := gostringn(err.error_string, findnull(err.error_string))
// or cgo one:
type senseiErr struct {
code C.int
error_string *C.char
}
...
error_string := C.GoString(err.error_string)
- 1 回答
- 0 關(guān)注
- 134 瀏覽
添加回答
舉報