duanbin3021 2018-09-13 08:15
浏览 277

如何在Go中返回切片并从C调用?

I am trying to use cgo to use Go package in C code. Following is a piece of my code:

func LinearTransformToUInt8(frame []int64, winWidth int, winCenter int) []uint8 {
    var transformed []uint8
    // my cool code
    return transformed
}

However, when calling from C, it says

panic: runtime error: cgo result has Go pointer

I believe the problem is the returned []uint8 is a Go type, which should be replaced by a C type. However, I don't know how to achieve it. Please help!

  • 写回答

1条回答 默认 最新

  • douge3113 2018-09-13 14:18
    关注

    main.go

    package main
    
    import (
        "C"
        "unsafe"
    )
    import (
        "reflect"
    )
    
    func main() {
    }
    
    //export phew
    func phew() uintptr {
        res := make([]uint8, 2)
        for i := 0; i < 2; i++ {
            res[i] = uint8(i + 1)
        }
        hdr := (*reflect.SliceHeader)(unsafe.Pointer(&res))
        return hdr.Data
    }
    

    main.c

    #include <stdio.h>
    #include <inttypes.h>
    
    #include "libtemp.h"
    
    int main(){
        uintptr_t resPtr = phew();
        uint8_t *res = (uint8_t*)resPtr;
    
        for (int i = 0; i < 2; i++){
            printf("%d
    ", res[i]);
        }
    
        printf("Exiting gracefully
    ");
    }
    

    You cannot pass a Go pointer which contains other Go Pointer, slice,string,channel,function, interface, map contain pointers.

    So one cannot pass them around, rules to passing around pointers are documented here and go's representation of basic types is documented here.

    But some Go contributors were saying, one shouldn't return a Go pointer to C code in the first place.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!