为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 Go 向 C 发送字节数组

如何从 Go 向 C 发送字节数组

Go
拉莫斯之舞 2023-07-31 16:42:17
我试图将一个字节数组从 GO 传递到 C 函数,但我不能这样做,这是我的代码:package main /* #include <stdint.h> #include "api.h" #include "parameters.h" #include "lilliput-ae.h" #include "tool.h" void print(void *b)  {    printf("%d",b[0]);    printf("%d",b[5]);  }  */  import "C"  import "unsafe"   func main() {     a := [16]byte{16, 8, 7, 4, 12, 6, 7, 8, 9, 10, 11, 7, 16, 14, 15, 1}     ptr := unsafe.Pointer(&a[0])     C.print(ptr)   }我的最终目标是打印像 uint8_t 数组这样的 C 代码,当我成功做到这一点时,我将尝试将数组从 C 代码发送到 Go。
查看完整描述

1 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

我将一个字节数组从 Go 传递到 C 函数。

我的目标是打印类似uint8_t数组的 C 代码。


对于你的例子,

package main


/*

#include <stdio.h>

#include <stdint.h>


void print(void *p) {

    uint8_t *b = p;

    printf("%d ",b[0]);

    printf("%d ",b[5]);

    printf("\n");

}

*/

import "C"


import (

    "fmt"

    "unsafe"

)


func main() {

    a := [16]byte{16, 8, 7, 4, 12, 6, 7, 8, 9, 10, 11, 7, 16, 14, 15, 1}

    fmt.Println(a)

    ptr := unsafe.Pointer(&a[0])

    C.print(ptr)

}

输出:


[16 8 7 4 12 6 7 8 9 10 11 7 16 14 15 1]

16 6 



查看完整回答
反对 回复 2023-07-31
  • 1 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信