Integrating existing C code to Go. Convert unsigned char poiner result to []byte

StackOverflow https://stackoverflow.com/questions/19060015

  •  29-06-2022
  •  | 
  •  

Pergunta

Here is a simple example:

package main

//#include <stdio.h>
//#include <strings.h>
//#include <stdlib.h>
/*
typedef struct {
    unsigned char *data;
    unsigned int data_len;
} Result;

Result *foo() {
    Result *r = malloc(sizeof(Result));

    r->data = (unsigned char *)malloc(10);
    r->data_len = 10;

    memset(r->data, 0, 10);

    r->data = (unsigned char *)strdup("xxx123");
    r->data_len = 6;

    return r;
}
*/
import "C"

import (
    "fmt"
    // "unsafe"
)

func main() {
    result := C.foo()

    fmt.Printf("%v, %v, %v\n", result.data, string(*(result.data)), result.data_len)
}

As a result i've got something like this

0x203970, x, 6

pointer to data, first character of data and the size. But how can i get the actual data value, preferably as a []byte type to use it in go code?
In other words - how to convert unsigned char * to []byte?

Foi útil?

Solução

You can do this with unsafe.Pointer and C.GoStringN:

data := (*C.char)(unsafe.Pointer(result.data))
data_len := C.int(result.data_len)

fmt.Println(C.GoStringN(data, data_len))

And the most simple way:

data := (*C.char)(unsafe.Pointer(result.data))
fmt.Println(C.GoString(data))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top