5

I would like to convert from a go [][]byte to a C **char. In other words, I have a byte matrix in go that I would like to convert to a char double pointer in C.

Please assume that I HAVE to have a [][]byte as input and a **char as output.

I know it is possible to convert from []byte to *char by doing something like:

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

But it does not seem possible to extend this case into the second dimension. I have tried something pretty elaborate, where I pack a [][]byte into a new []byte. I then send that []byte to a C function that creates a **char using pointer arithmetic to point into the new []byte at the correct locations.

This conversion is giving me strange behaviour though, where my data would be correct for a few iterations, but gets corrupted seemingly between function calls.

If anyone has any ideas, I would really appreciate it.

From the responses I see it is also important to state that I'm working with raw data and not strings. Hence the go byte type. The original data would, therefore, be corrupted if C string terminators are added. I'm just using C **char, because a char is one byte in size. That said, thanks for the responses. I was able to adapt the accepted answer for my needs.

2 Answers 2

4

Untested skeleton:

func foo(b [][]byte) {
        outer := make([]*C.char, len(b)+1)
        for i, inner := range b {
                outer[i] = C.CString(string(inner))
        }
        C.bar(unsafe.Pointer(&outer[0])) // void bar(**char) {...}
}

EDIT: Full example (tested):

package main

/*
#include <stdlib.h>
#include <stdio.h>

void bar(char **a) {
        char *s        ;
        for (;(s = *a++);)
                printf("\"%s\"\n", s);
}
*/
import "C"
import "unsafe"

func foo(b [][]byte) {
        outer := make([]*C.char, len(b)+1)
        for i, inner := range b {
                outer[i] = C.CString(string(inner))
        }
        C.bar((**C.char)(unsafe.Pointer(&outer[0]))) // void bar(**char) {...}
}

func main() {
        foo([][]byte{[]byte("Hello"), []byte("world")})
}

(15:24) jnml@fsc-r550:~/src/tmp/SO/14833531$ go run main.go 
"Hello"
"world"
(15:25) jnml@fsc-r550:~/src/tmp/SO/14833531$ 
2
  • What does your example do? Could you elaborate a bit, additionally to your code?
    – Kissaki
    Feb 16, 2013 at 15:09
  • The example converts a Go [][]byte to a null terminated C **char, which is then printed out at the C side. Is that what you're asking about? If not, please elaborate a bit on your question.
    – zzzz
    Feb 16, 2013 at 15:29
3

This has to be done manually. You have to allocate a new **C.char type and loop through each element in the [][]byte slice to assign it to the new list. This involves offsetting the **C.char pointer by the correct size for each iteration.

Here is an example program which does this.

As the comments below suggest, if you intend to print the char * lists using something like printf in C, then ensure the input strings are NULL terminated. Ideally by converting them using the C.CString() function. This assumes that they are to be treated as strings though. Otherwise you may also need to supply a way to pass the length of each individual char * list to the C function.

package main

/*
#include <stdlib.h>
#include <stdio.h>

void test(char **list, size_t len)
{
    size_t i;

    for (i = 0; i < len; i++) {
        //printf("%ld: %s\n", i, list[i]);
    }
}
*/
import "C"
import "unsafe"

func main() {
    list := [][]byte{
        []byte("foo"),
        []byte("bar"),
        []byte("baz"),
    }

    test(list)
}

func test(list [][]byte) {
    // Determine the size of a pointer on the current system.
    var b *C.char
    ptrSize := unsafe.Sizeof(b)

    // Allocate the char** list.
    ptr := C.malloc(C.size_t(len(list)) * C.size_t(ptrSize))
    defer C.free(ptr)

    // Assign each byte slice to its appropriate offset.
    for i := 0; i < len(list); i++ {
        element := (**C.char)(unsafe.Pointer(uintptr(ptr) + uintptr(i)*ptrSize))
        *element = (*C.char)(unsafe.Pointer(&list[i][0]))
    }

    // Call our C function.
    C.test((**C.char)(ptr), C.size_t(len(list)))
}

The output is as follows:

$ go run charlist.go 
0: foo
1: bar
2: baz
5
  • 1
    I don't think you've null terminated the C strings have you? Your example worked but I suspect you got lucky! Feb 12, 2013 at 20:02
  • Quite right. The line *element = (*C.char)(unsafe.Pointer(&list[i][0])) should ideally read *element = C.CString(string(list[i]))
    – jimt
    Feb 13, 2013 at 0:49
  • Wait, why does the C structure have to be null terminated? Please don't assume that I'm working with strings. I'm working with raw data buffers. Does the string function still have to be used then? Feb 13, 2013 at 6:39
  • 1
    A char * does have to be null terminated if you pass it to printf like @jmt did in the example. In general it doesn't though of course, but I would expect you'd want the length too unless each blob of data is self describing or of fixed length. Feb 13, 2013 at 9:00
  • 1
    Yes, I'm working with fixed size data buffers so I know the length. I see what you mean that to print out the data as a string you want to null terminate it. I would then suggest that if the post is changed that the null terminator rather be added somewhere else, since by adding a null terminator to be able to print out raw data, you're corrupting the original data. Feb 13, 2013 at 9:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.