Search code examples
cgocgo

cgo Copy gobytes into c array


I am reading go documentation and trying sample to complete the main requirement. I spent lot of time on this problem, but couldn't solve the issue.

In my project the requirement is to to copy go byte data into C.char array[10] , a C structure data variable. I checked C.CBytes(), but that creates new memory. looking for something similar to copy()
Below sample code where I tried to replicate my original requirement.

package main
import "C"
/*
#include <stdio.h>
#include <string.h>
struct name {
 char fname[10];
 char lname[10];
};

struct infor{
   name ID[1];
   int id;
};

int receive(struct infor *c){
   printf("%s",c.ID.fname);
   printf("\n %s", c.id);
}
*/

type data struct {
        n [10]byte
        m [10]byte
}

func main(){
  d := data{}
  d.n = []byte("test1")
  d.m = []byte("test2")
  obj := C.struct_infor{}
  obj.ID.fname = d.n

}


Solution

  • You could use strcpy in string.h. Following is a working example:

    package main
    
    /*
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct mystruct {
        char field[10];
    };
    
    */
    import "C"
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        x := new(C.struct_mystruct)
        bts := []byte("some text")
        C.strcpy((*C.char)(unsafe.Pointer(&x.field[0])), (*C.char)(unsafe.Pointer(&bts[0])))
        fmt.Printf("%#v", x)
    }
    

    The important part is that you have to get an unsafe pointer of the first element and convert it to *C.char for this to work