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

我试图将一个字节数组从 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。


拉莫斯之舞
浏览 78回答 1
1回答

catspeake

我将一个字节数组从 Go 传递到 C 函数。我的目标是打印类似uint8_t数组的 C 代码。对于你的例子,package main/*#include <stdio.h>#include <stdint.h>void print(void *p) {&nbsp; &nbsp; uint8_t *b = p;&nbsp; &nbsp; printf("%d ",b[0]);&nbsp; &nbsp; printf("%d ",b[5]);&nbsp; &nbsp; printf("\n");}*/import "C"import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "unsafe")func main() {&nbsp; &nbsp; a := [16]byte{16, 8, 7, 4, 12, 6, 7, 8, 9, 10, 11, 7, 16, 14, 15, 1}&nbsp; &nbsp; fmt.Println(a)&nbsp; &nbsp; ptr := unsafe.Pointer(&a[0])&nbsp; &nbsp; C.print(ptr)}输出:[16 8 7 4 12 6 7 8 9 10 11 7 16 14 15 1]16 6&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP