FAQ
I've got a cgo question - I've got a C library call that returns a
**char, which is a null-terminated array of null-terminated strings.
Can anyone help me out with a good way to convert it to a []string?
I've figured out how to go the other way pretty easily, and when I've
cleaned it up a bit I hope to put it on the cgo wiki page
(http://code.google.com/p/go-wiki/wiki/cgo)
Thanks,
Luke

--

Search Discussions

  • Rémy Oudompheng at Oct 1, 2012 at 10:07 pm

    On 2012/10/1 Luke Roth wrote:
    I've got a cgo question - I've got a C library call that returns a
    **char, which is a null-terminated array of null-terminated strings.
    Can anyone help me out with a good way to convert it to a []string?
    I've figured out how to go the other way pretty easily, and when I've
    cleaned it up a bit I hope to put it on the cgo wiki page
    (http://code.google.com/p/go-wiki/wiki/cgo)
    Thanks,
    Luke
    Something like:

    var p **char = ...
    var s []string
    q := uintptr(unsafe.Pointer(p))
    for {
    p = (**char)(unsafe.Pointer(q))
    if *p == nil {
    break
    }
    s = append(s, C.GoString(*p))
    p += unsafe.SizeOf(*char)
    }

    Rémy.

    --
  • Luke Roth at Oct 2, 2012 at 1:29 am
    Thanks! I hadn't realized that it was possible to do pointer
    arithmetic that way in Go. I haven't tested this exhaustively, but
    I've gotten that code to build with just a couple of minor changes:

    p := C.FuncThatReturnsNullTerminatedCharArray() // returns **char
    var strings []string
    q := uintptr(unsafe.Pointer(p))
    for {
    p = (**C.char)(unsafe.Pointer(q))
    if *p == nil {
    break
    }
    strings = append(strings, C.GoString(*p))
    q += unsafe.Sizeof(q)
    }

    Luke

    On Mon, Oct 1, 2012 at 6:01 PM, Rémy Oudompheng
    wrote:
    On 2012/10/1 Luke Roth wrote:
    I've got a cgo question - I've got a C library call that returns a
    **char, which is a null-terminated array of null-terminated strings.
    Can anyone help me out with a good way to convert it to a []string?
    I've figured out how to go the other way pretty easily, and when I've
    cleaned it up a bit I hope to put it on the cgo wiki page
    (http://code.google.com/p/go-wiki/wiki/cgo)
    Thanks,
    Luke
    Something like:

    var p **char = ...
    var s []string
    q := uintptr(unsafe.Pointer(p))
    for {
    p = (**char)(unsafe.Pointer(q))
    if *p == nil {
    break
    }
    s = append(s, C.GoString(*p))
    p += unsafe.SizeOf(*char)
    }

    Rémy.
    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedOct 1, '12 at 9:32p
activeOct 2, '12 at 1:29a
posts3
users2
websitegolang.org

2 users in discussion

Luke Roth: 2 posts Rémy Oudompheng: 1 post

People

Translate

site design / logo © 2021 Grokbase