繁体   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