Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From []byte to char*

Tags:

c

pointers

go

cgo

I want to wrap a C function that takes a char* pointing to (the first element of) a non-empty buffer of bytes. I'm trying to wrap that in a Go function using CGo so that I can pass it a []byte, but I don't know how to do the conversion. A simplified version of the C function's signature is

void foo(char const *buf, size_t n);

I tried passing a pointer to the first byte in the slice with

C.foo(&b[0], C.size_t(n))

That doesn't compile, though:

cannot use &b[0] (type *byte) as type *_Ctype_char in function argument

So what's the correct procedure here? The go-wiki only describes the reverse situation.

like image 895
Fred Foo Avatar asked May 04 '13 15:05

Fred Foo


People also ask

Can we convert byte to char?

This is the code: char a = 'È'; // line 1 byte b = (byte)a; // line 2 char c = (char)b; // line 3 System. out. println((char)c + " " + (int)c);

What does byte [] do in Java?

The byte keyword is a data type that can store whole numbers from -128 to 127.

What is Class for byte [] in Java?

Byte class is a wrapper class for the primitive type byte which contains several methods to effectively deal with a byte value like converting it to a string representation, and vice-versa. An object of Byte class can hold a single byte value. Byte class offers four constants in the form of Fields.


1 Answers

Ok, that turned out to be much easier than I thought:

(*C.char)(unsafe.Pointer(&b[0]))

does the trick. (Found this at golang-nuts.)

like image 162
Fred Foo Avatar answered Oct 18 '22 15:10

Fred Foo