在C中使用Go slice [英] Use Go slice in C

查看:66
本文介绍了在C中使用Go slice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用返回切片的函数来构建go共享库.
如何使用C代码中的切片?

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() {}

开始构建-o lib.so -buildmode = c-shared main.go

我现在有一个 lib.so 和一个 lib.h

打印数组值的C代码是什么?

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\n", ((T *)a.data)[i].B);
  }
}

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

推荐答案

在C语言中使用Go切片

Use Go slice in C


以下是C打印Go byte 切片的示例:

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("]\n");
}
*/
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)
}

输出:

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


func Test()[] T 的C返回值错误.返回长度和数组指针,例如 cbuf .


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

这篇关于在C中使用Go slice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆