Search code examples
arraysgocgo

How to send byte array from Go to C


I'm trying to pass a byte array from GO to C function, but I can't do that, there is my code:

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)
   }

My final objective is to print C code like uint8_t array, and when I will succeed to do that, I will try to send the array from C code to Go.


Solution

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

    My objective is to print C code like uint8_t array.


    For your example,

    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)
    }
    

    Output:

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