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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line