CGO的奇怪操作 持续更新
mousemin 2023/4/23 go
主要记录下 cgo
一些写发与实际想法不同的地方.
# 数组传递
cgo
中 go
往 c
传递数组时, 直接传递数组会报错, 正确的传递方式是传递 数组中第1个元素的地址.
package main
/*
#include <stdio.h>
#include <string.h>
int sum(int sizes[], int num, int p[]) {
int sum = 0;
if (p == NULL) {
return 0;
}
for (int i = 0; i < num; i++) {
sum += p[i];
sizes[i] = p[i];
printf("%d, %d\n", i, p[i]);
}
return sum;
}
*/
import "C"
import (
"fmt"
)
func main() {
sizes := []C.int{0, 0, 0, 0, 0}
p := []C.int{C.int(1), C.int(2), C.int(3), C.int(4), C.int(5)}
// sum := C.sum(sizes, C.int(5), p)
// 报错
// ./cgo.go:30:15: cannot use sizes (variable of type []_Ctype_int) as type *_Ctype_int in argument to (_Cfunc_sum)
// ./cgo.go:30:32: cannot use p (variable of type []_Ctype_int) as type *_Ctype_int in argument to (_Cfunc_sum)
sum := C.sum(&sizes[0], C.int(5), &p[0])
fmt.Printf("%T\n", int(sum))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35