gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:41 25 4
gpt4 key购买 nike

我想将 uint8_t 数组从 C 发送到 GO,但是当我像指针一样发送我的数组时,我不知道如何读取它并将它像字节 [] 数组一样保存在 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( )
{
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}

我尝试了很多解决方案,但每次我都有日志说“不能使用 (func literal)() (type *_Ctype_uchar) as type"uint8"or "byte"...

谢谢大家的帮助!

最佳答案

I want to send uint8_t array from C to Go [and as an array or a slice]


以你的例子为例,

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 (
"fmt"
"math"
"unsafe"
)

func main() {
// your example
data := (*[16]byte)(unsafe.Pointer(C.send_data()))
fmt.Printf("\n%T:\n%d %d : %v\n", data, len(data), cap(data), *data)

// array example
const c = 16 // array length is constant
a := (*[c]byte)(unsafe.Pointer(C.send_data()))
fmt.Printf("\n%T:\n%d %d : %v\n", a, len(a), cap(a), *a)

// slice example
var v = 16 // slice length is variable
var s []byte
const vmax = math.MaxInt32 / unsafe.Sizeof(s[0])
s = (*[vmax]byte)(unsafe.Pointer(C.send_data()))[:v:v]
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]

关于c - 如何将 uint8_t 数组从 C 发送到 GO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58673984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com