John Gilmore
John Gilmore

Reputation: 2815

How to convert from [][]byte to **char in go

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.

Upvotes: 5

Views: 3900

Answers (2)

jimt
jimt

Reputation: 26410

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

Upvotes: 3

zzzz
zzzz

Reputation: 91253

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$ 

Upvotes: 4

Related Questions