将现有的C代码集成到Go中。将无符号字符指针的结果转换为[]byte类型。

huangapple go评论77阅读模式
英文:

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

问题

这是一个简单的示例:

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

英文:

Here is a simple example:

package main

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

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

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

	memset(r-&gt;data, 0, 10);

	r-&gt;data = (unsigned char *)strdup(&quot;xxx123&quot;);
	r-&gt;data_len = 6;

	return r;
}
*/
import &quot;C&quot;

import (
	&quot;fmt&quot;
	// &quot;unsafe&quot;
)

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

	fmt.Printf(&quot;%v, %v, %v\n&quot;, 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?

答案1

得分: 3

你可以使用unsafe.PointerC.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))
英文:

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

huangapple
  • 本文由 发表于 2013年9月28日 05:02:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/19060015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定