cgo:go数组转c数组调用c函数

package main

/*
#include <stdio.h>

void processInt2DArray(int* arr, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", *(arr + i * cols + j));
        }
        printf("\n");
    }
}
*/
import "C"

func main() {
    // 创建一个 Go 中的二维整数数组
    goInt2DArray := [][]C.int{
        {1, 2},
        {4, 6},
        {7, 8},
        {2, 6},
    }
    cIntArray := [4][2]C.int{
        {C.int(goInt2DArray[0][0]), C.int(goInt2DArray[0][1])},
        {C.int(goInt2DArray[1][0]), C.int(goInt2DArray[1][1])},
        {C.int(goInt2DArray[2][0]), C.int(goInt2DArray[2][1])},
        {C.int(goInt2DArray[3][0]), C.int(goInt2DArray[3][1])},
    }
    // 获取数组的指针并传递给 C 函数
    rows := len(goInt2DArray)
    cols := len(goInt2DArray[0])
    C.processInt2DArray(&cIntArray[0][0], C.int(rows), C.int(cols))
}

 

posted @ 2023-12-07 20:48  七星易  阅读(48)  评论(0编辑  收藏  举报