3

这是一个简单的例子:

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)
}

结果我得到了这样的东西

0x203970, x, 6

指针data,第一个字符data和大小。但是我怎样才能得到实际data值,最好是作为 []byte 类型在 go 代码中使用它?
换句话说 - 如何转换unsigned char *[]byte

4

1 回答 1

1

你可以用unsafe.Pointerand做到这一点C.GoStringN

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

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

还有最简单的方法:

data := (*C.char)(unsafe.Pointer(result.data))
fmt.Println(C.GoString(data))
于 2013-09-27T21:15:26.533 回答