duanjuelian4640 2018-07-25 18:54
浏览 256

在C中使用Go slice

I'm trying to build a go shared library with a function that returns a slice.
How can I use the slice from C code ?

package main

import "C"

type T struct {
    A C.int
    B *C.char
}

//export Test
func Test() []T {
    arr := make([]T, 0)
    arr = append(arr, T{C.int(1), C.CString("a")})
    arr = append(arr, T{C.int(2), C.CString("abc")})
    return arr
}

func main() {}

go build -o lib.so -buildmode=c-shared main.go

I now have a lib.so and a lib.h

What would be the C code to print the values of the array ?

#include <stdio.h>
#include "lib.h"

typedef struct {
  int   A;
  char* B;
} T;

int main() {
  GoSlice a = Test();
  for (int i = 0; i < 2; i++){
    printf("%s
", ((T *)a.data)[i].B);
  }
}

gcc -o main main.c ./lib.so

  • 写回答

2条回答 默认 最新

  • douchengfei3985 2018-07-25 19:29
    关注

    Use Go slice in C


    Here's an example of C printing a Go byte slice:

    package main
    
    /*
    #include <stdio.h>
    
    void printbuf(size_t len, unsigned char *buf) {
        printf("%lu [", len);
        if (!buf) {
            len = 0;
        }
        size_t maxwidth = 16;
        size_t width = len <= maxwidth ? len : maxwidth;
        for (size_t i = 0; i < width; i++) {
            if (i > 0) {
                printf(" ");
            }
            printf("%02X", buf[i]);
        }
        if (width < len) {
            printf(" ...");
        }
        printf("]
    ");
    }
    */
    import "C"
    
    func cbuf(buf []byte) (size C.size_t, ptr *C.uchar) {
        var bufptr *byte
        if cap(buf) > 0 {
            bufptr = &(buf[:1][0])
        }
        return C.size_t(len(buf)), (*C.uchar)(bufptr)
    }
    
    func main() {
        buf := make([]byte, 24, 32)
        for i := range buf {
            buf[i] = byte(i)
        }
        bufsize, bufptr := cbuf(buf)
        C.printbuf(bufsize, bufptr)
    }
    

    Output:

    24 [00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ...]
    

    func Test() []T has the wrong return values for C. Return a length and an array pointer, like cbuf.

    评论

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?