Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go []string to C char**

Tags:

c

types

go

I started trying to integrate some C libraries into my Go code for a project using cgo and have come across a problem.

In one of the C functions I need to pass argv to a function call. In C argv is a pointer to an array of char strings (K&R C, §5.10) and I need to convert from a slice of strings to a char**.

I have had a good look, high and low for any information on how to do variable type conversions from Go to C but there appears to be next to no documentation. Any help would be appreciated.

like image 556
onmylemon Avatar asked Jan 16 '14 09:01

onmylemon


1 Answers

You'll need to create the array yourself. Something like this should do:

argv := make([]*C.char, len(args))
for i, s := range args {
    cs := C.CString(s)
    defer C.free(unsafe.Pointer(cs))
    argv[i] = cs
}
C.foo(&argv[0])
like image 115
James Henstridge Avatar answered Sep 22 '22 11:09

James Henstridge