簡體   English   中英

難以傳遞和訪問從 C 到 Go 的指針

[英]Difficulty passing and access a pointer from C to Go

我有一個用 C 編寫的串行庫,它有一個 rx 回調。 我們在此回調 function 中訪問通過串行鏈路接收的字節。 我想將收到的字節傳遞給用 Go 編寫的應用程序層。 為此,我已經能夠從 C Rx 回調中調用 go function。

但是,當我嘗試將指向 rx 字節的指針傳遞給 Go function 時,我沒有得到預期的結果。

我編寫了一個示例程序,其中 C function 返回指向 Go ZC1C4145268E687A945D 的指針。

我的期望: hello會被打印出來

實際結果:

%!s(*uint8=0xc000018072)

這是一個測試程序來說明我正在嘗試做的事情:

package main
//#include <stdint.h>
// extern void goHandler(uint8_t *str);
//
// static void doPrint(uint8_t *str) {
//     goHandler(str);
// }
import "C"
import "fmt"

//export goHandler
func goHandler(str *uint8)  {
        fmt.Printf("%s\n",str)
}

func main()  {
   bytes := []uint8("hello")
   C.doPrint((*C.uchar)(&bytes[0]))
}

編輯:我了解了執行指針運算以訪問指針地址偏移處的數據,但是有沒有辦法將整個數據從偏移量 0 傳遞到特定的偏移量(不是一個接一個?)

我試過了,它很有效,可能比其他任何方式都好:

package main
//#include <stdint.h>
// extern void goHandler(uint8_t *str, uint8_t length);
//
// static void doPrint(uint8_t *str, uint8_t length) {
//     goHandler(str, length);
// }
import "C"
import "fmt"
import "unsafe"

//export goHandler
func goHandler(str *uint8, length uint8)  {
        b := *(*[1<<20]byte)(unsafe.Pointer(str))
        fmt.Printf("%s\n",b[0:length])
}

func main()  {
   bytes := []uint8("hello")
   C.doPrint((*C.uchar)(&bytes[0]), C.uchar(len(bytes)))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM