亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

直接C指針轉換

直接C指針轉換

Go
四季花海 2023-05-08 14:58:19
我有這個 C 代碼:uint8_t *data[BUF_SIZE];data = ...;// extern void goReadData(uint8_t *data, int bufferSize);goReadData(data, BUF_SIZE)在 GO 代碼中,我試圖將data指針用作 GO 數組或切片,我想從 *C.uint8_t 中檢索一個 []uint8。我知道尺寸data//export goReadDatafunc goReadData(data *C.uint8_t, bufferSize C.int) {    fmt.Printf("Data type %v\n", reflect.TypeOf(data))    // print 1: Data type *main._Ctype_uchar    // Solution 1: GoBytes    // works but really slow (memory copy I think)    goBytes := C.GoBytes(unsafe.Pointer(data), bufferSize)    fmt.Printf("goBytes type %v\n", reflect.TypeOf(goBytes))    // print 2: goBytes type []uint8    // Solution 2: direct pointer    // Really fast, but wrong type at the end    // unsafe.Pointer to the C array    unsafePtr := unsafe.Pointer(data)    // convert unsafePtr to a pointer of the type *[1 << 30]C.uint8_t    arrayPtr := (*[1 << 30]C.uint8_t)(unsafePtr)    // slice the array into a Go slice, with the same backing array    // as data, making sure to specify the capacity as well as    // the length.    length := int(bufferSize)    slice := arrayPtr[0:length:length]    fmt.Printf("Direct slice type %v\n", reflect.TypeOf(slice))    //Print 3: Direct type []main._Ctype_uchar}我該怎么做才能[]uint8用第二種解決方案恢復 an 而不是 []main._Ctype_uchar?或者您是否有另一種解決方案可以在沒有字節副本的情況下做到這一點?
查看完整描述

1 回答

?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

抱歉,我發現了自己的錯誤:

// convert unsafePtr to a pointer of the type *[1 << 30]C.uint8_t
arrayPtr := (*[1 << 30]C.uint8_t)(unsafePtr)

==>到

// convert unsafePtr to a pointer of the type *[1 << 30]uint8
arrayPtr := (*[1 << 30]uint8)(unsafePtr)

問題解決了!

謝謝 ;)


查看完整回答
反對 回復 2023-05-08
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號