CGO的奇怪操作 持续更新

2023-06-10 17:47:00 浏览数 (1)

CGO的奇怪操作 持续更新

主要记录下 cgo 一些写发与实际想法不同的地方.

数组传递

cgogoc 传递数组时, 直接传递数组会报错, 正确的传递方式是传递 数组中第1个元素的地址.

代码语言:javascript复制
 1package main
 2
 3/*
 4#include <stdio.h>
 5#include <string.h>
 6
 7int sum(int sizes[], int num, int p[]) {
 8    int sum = 0;
 9    if (p == NULL) {
10        return 0;
11    }
12    for (int i = 0; i < num; i  ) {
13        sum  = p[i];
14        sizes[i] =  p[i];
15        printf("%d, %dn", i, p[i]);
16    }
17    return sum;
18}
19
20*/
21import "C"
22import (
23	"fmt"
24)
25
26func main() {
27	sizes := []C.int{0, 0, 0, 0, 0}
28	p := []C.int{C.int(1), C.int(2), C.int(3), C.int(4), C.int(5)}
29  // sum := C.sum(sizes, C.int(5), p)
30  // 报错 
31  //    ./cgo.go:30:15: cannot use sizes (variable of type []_Ctype_int) as type *_Ctype_int in argument to (_Cfunc_sum)
32  //    ./cgo.go:30:32: cannot use p (variable of type []_Ctype_int) as type *_Ctype_int in argument to (_Cfunc_sum)
33	sum := C.sum(&sizes[0], C.int(5), &p[0])
34	fmt.Printf("%Tn", int(sum))
35}

0 人点赞