难以传递和访问从 C 到 Go 的指针
Difficulty passing and access a pointer from C to Go
我有一个用 C 编写的串行库,它有一个 rx 回调。我们在此回调函数中访问通过串行 link 接收的字节。我想将接收到的字节传递给用 Go 编写的应用程序层。为此,我已经能够从 C Rx 回调中调用一个 go 函数。
但是,当我尝试将指向 rx 字节的指针传递给 Go 函数时,我没有得到我期望的结果。
我写了一个示例程序,其中 C 函数 returns 指向 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 传递到特定偏移量(而不是一个一个地传递? )
我试过了,效果很好,可能比其他任何方法都好:
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)))
}
我有一个用 C 编写的串行库,它有一个 rx 回调。我们在此回调函数中访问通过串行 link 接收的字节。我想将接收到的字节传递给用 Go 编写的应用程序层。为此,我已经能够从 C Rx 回调中调用一个 go 函数。
但是,当我尝试将指向 rx 字节的指针传递给 Go 函数时,我没有得到我期望的结果。
我写了一个示例程序,其中 C 函数 returns 指向 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 传递到特定偏移量(而不是一个一个地传递? )
我试过了,效果很好,可能比其他任何方法都好:
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)))
}