duanhe6718 2013-09-27 21:02
浏览 54
已采纳

将现有的C代码集成到Go中。 将未签名的字符修饰符结果转换为[] 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
", 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条回答 默认 最新

  • douxian9706 2013-09-27 21:15
    关注

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)