Convert char* (C String) to GO string in cgo

10,058 views
Skip to first unread message

Adrian

unread,
Aug 18, 2010, 2:38:19 PM8/18/10
to golang-nuts
Hi,

How do I convert from a C null terminated string (char*) to a GO
string in cgo?

If I have a "C" function as say:

char* getString()
{
return "blah";
}

How can I get a GO string when calling getString()?

Thanks.

Russ Cox

unread,
Aug 18, 2010, 2:54:54 PM8/18/10
to Adrian, golang-nuts
C.GoString(C.getString()) will work.
Normally you'd have to save the
C pointer so you can free it:

p := C.getString()
s := C.GoString(p)
C.free(unsafe.Pointer(p))

Russ

Russ Cox

unread,
Aug 18, 2010, 3:07:19 PM8/18/10
to Eric Clark, golang-nuts
On Wed, Aug 18, 2010 at 15:03, Eric Clark <zer...@gmail.com> wrote:
> As a related question, I have a C library which uses strings that can
> contain \0 characters, so I have both both char* and size_t* for the
> length.  Is there a 2 argument version of GoString that I can use?

Unfortunately, no. Please file an issue.

Russ

Adrian

unread,
Aug 18, 2010, 3:20:45 PM8/18/10
to golang-nuts
Hi

Thanks for that.
Guess I would have to take care of freeing the string only when the
function returns a newly allocated string right?
Had I (as I should have actually) written the getString function to
return a const char* (as that is what it is returning), then I
wouldn't have to be bothered about freeing the memory right?

Russ Cox

unread,
Aug 18, 2010, 3:27:50 PM8/18/10
to Adrian, golang-nuts
> Guess I would have to take care of freeing the string only when the
> function returns a newly allocated string right?
> Had I (as I should have actually) written the getString function to
> return a const char* (as that is what it is returning), then I
> wouldn't have to be bothered about freeing the memory right?

You should only free it if it's your job to free it,
like in any C program. Whether the pointer is
const or not is a completely separate issue.

Russ

Reply all
Reply to author
Forward
0 new messages