如何将 uint8_t 数组从 C 发送到 GO

我想将 uint8_t 数组从 C 发送到 GO,但是当我像指针一样发送数组时,我不知道如何读取它并将其保存在 GO 中,例如 byte[] 数组:


package main

/*

#include <stdint.h>


uint8_t Plaintext[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};


uint8_t * send_data( )

   {

     return  Plaintext;

   }


*/

import "C"

import "unsafe"

import "fmt"


func main() {


    data := [16]byte{}

    p := C.send_data()

    //already try  data = C.send_data()

    fmt.Println(p)

    data = p // don't know how do this ?


}

objectif 是在 go 中包含数据字节数组,如下所示:


data[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}

我尝试了很多解决方案,但每次我有日志说“不能使用(funcliteral)()(类型*_Ctype_uchar)作为类型“uint8”或“byte”...


不负相思意
浏览 142回答 1
1回答

桃花长相依

我想将 uint8_t 数组从 C 发送到 Go [并且作为数组或切片]对于你的例子,package main/*#include <stdint.h>uint8_t Plaintext[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};uint8_t *send_data( ) {&nbsp; &nbsp; return&nbsp; Plaintext;}*/import "C"import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math"&nbsp; &nbsp; "unsafe")func main() {&nbsp; &nbsp; // your example&nbsp; &nbsp; data := (*[16]byte)(unsafe.Pointer(C.send_data()))&nbsp; &nbsp; fmt.Printf("\n%T:\n%d %d : %v\n", data, len(data), cap(data), *data)&nbsp; &nbsp; // array example&nbsp; &nbsp; const c = 16 // array length is constant&nbsp; &nbsp; a := (*[c]byte)(unsafe.Pointer(C.send_data()))&nbsp; &nbsp; fmt.Printf("\n%T:\n%d %d : %v\n", a, len(a), cap(a), *a)&nbsp; &nbsp; // slice example&nbsp; &nbsp; var v = 16 // slice length is variable&nbsp; &nbsp; var s []byte&nbsp; &nbsp; const vmax = math.MaxInt32 / unsafe.Sizeof(s[0])&nbsp; &nbsp; s = (*[vmax]byte)(unsafe.Pointer(C.send_data()))[:v:v]&nbsp; &nbsp; fmt.Printf("\n%T:\n%d %d : %v\n", s, len(s), cap(s), s)}输出:[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]*[16]uint8:16 16 : [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15][]uint8:16 16 : [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go