英文:
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 <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
?
答案1
得分: 3
你可以使用unsafe.Pointer
和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))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论