如何将字节数组从Go发送到C

How to send byte array from Go to 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)
   }

我最后的 objective 是打印 C 代码,如 uint8_t 数组,当我成功完成时,我会尝试将数组从 C 代码发送到 Go。

I'm passing a byte array from Go to C function.

My objective is to print C code like uint8_t array.


以你的例子为例,

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