【问题标题】:Difficulty passing and access a pointer from C to Go难以传递和访问从 C 到 Go 的指针
【发布时间】:2021-06-29 16:51:03
【问题描述】:

我有一个用 C 编写的串行库,它有一个 rx 回调。我们在此回调函数中访问通过串行链路接收的字节。我想将收到的字节传递给用 Go 编写的应用程序层。为此,我已经能够从 C Rx 回调中调用 go 函数。

但是,当我尝试将指向 rx 字节的指针传递给 Go 函数时,我没有得到预期的结果。

我编写了一个示例程序,其中 C 函数返回指向 Go 函数的指针。

我的期望: 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 传递到特定的偏移量(不是一个接一个?)

【问题讨论】:

    标签: c go pointers cgo


    【解决方案1】:

    我试过了,它很有效,可能比其他任何方法都好:

    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)))
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-20
      • 2021-07-09
      • 1970-01-01
      • 2013-04-03
      • 2011-03-15
      • 2018-12-31
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多