Passing []byte from golang to char * C.

737 views
Skip to first unread message

aditi.bh...@gmail.com

unread,
Jun 14, 2017, 10:00:05 AM6/14/17
to golang-nuts
I have a byte array of image in golang , i have to pass this array to my C function as char* . I did he following ,
         data, err := ioutil.ReadAll(out.Body)
         str := fmt.Sprintf("%s",data)
         s:=C.main1(C.CString(str))
         s:=C.main1((*C.char)(unsafe.Pointer(&data[0])))
but both the technique doesn't work. All i m receiving in my C function is some garbage value of length 4. 

andrey mirtchovski

unread,
Jun 14, 2017, 11:47:10 AM6/14/17
to aditi.bh...@gmail.com, golang-nuts
can you show us a complete example with a stub C function? in
particular the conversion to (*C.char) from unsafe.Pointer(&data[0])
should work. compare the first four bits at that address with the
first four bits you're receiving on the C side. they should be
identical. e.g.: https://play.golang.org/p/sqP12_nJNF
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Tamás Gulácsi

unread,
Jun 14, 2017, 12:05:39 PM6/14/17
to golang-nuts
Both should work. What is your C function?

Aditi Bhiwaniwala

unread,
Jun 15, 2017, 1:04:36 AM6/15/17
to andrey mirtchovski, golang-nuts
the error occur because there is 0 in my byte array . Do i need to encode it then?

Tamás Gulácsi

unread,
Jun 15, 2017, 8:51:03 AM6/15/17
to golang-nuts
C strings are 0-terminated. Either encode 0 (byte) values, or call with pointer to first byte, and the length.
Reply all
Reply to author
Forward
0 new messages