CGO and char[] array to string

6,056 views
Skip to first unread message

Tech163

unread,
Feb 16, 2013, 11:19:57 AM2/16/13
to golang-nuts
I'm trying to get the uname of a server through the C api through CGO. I
have

#include <sys/utsname.h>

var utsname C.struct_utsname
C.uname(&utsname)

I'm trying to do string(utsname.sysname), but I'm getting an error
"cannot convert utsname.sysname (type [65]_Ctype_char) to type string".
How can I convert that char[] to a string in Go?

I understand that in this specific case I can just read /proc/version,
etc, but I'm curious how char[] can be converted to string.

Any help would be appreciated.

Thanks!

--
Tech163

Jan Mercl

unread,
Feb 16, 2013, 11:25:03 AM2/16/13
to Tech163, golang-nuts
On Sat, Feb 16, 2013 at 5:19 PM, Tech163 <tec...@sliceone.com> wrote:
> I understand that in this specific case I can just read /proc/version, etc,
> but I'm curious how char[] can be converted to string.

Use the CGO[1] provided helpers:

> A few special functions convert between Go and C types by making copies of the data. In pseudo-Go definitions:
>
> // Go string to C string
> // The C string is allocated in the C heap using malloc.
> // It is the caller's responsibility to arrange for it to be
> // freed, such as by calling C.free.
> func C.CString(string) *C.char
>
> // C string to Go string
> func C.GoString(*C.char) string
>
> // C string, length to Go string
> func C.GoStringN(*C.char, C.int) string
>
> // C pointer, length to Go []byte
> func C.GoBytes(unsafe.Pointer, C.int) []byte

[1]: http://golang.org/cmd/cgo/

-j

Tech163

unread,
Feb 16, 2013, 1:14:19 PM2/16/13
to Jan Mercl, golang-nuts
Thanks.

C.GoString(&utsname.sysname[0])

seems to work well.

Tech163
Reply all
Reply to author
Forward
0 new messages