cgo中向C部分函数传入go的slice

注意事项:

传入C函数中的slice需要以&array[0]的形式进行,而不能单纯使用&array,因为go中的slice数据结构不仅仅具有首地址。

类型对应表

type C go
char C.char byte
signed C.schar int8
unsigned char C.uchar uint8
short int C.short int16
short unsigned int C.ushort uint16
int C.int int
unsigned int C.uint uint32
long int C.long int32/int64
long unsigned int C.ulong uint32/uint64
long long int C.longlong int64
long long unsigned int C.ulonglong uint64
float C.float float32
double C.double float64
wchar_t C.wchar_t
void * unsafe.Pointer

例子

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
36
37
38
package main

/*
struct test_t{
int a;
};

void setInt(void *t){
unsigned long *arr = (unsigned long *)t;
for(int i=0;i<10;i++){
arr[i] = i;
}
}

void setTest(void *t){
struct test_t *m = (struct test_t *)t;
m->a = 10;
}
*/
// #cgo 386 CFLAGS: -DX86=1
import "C"
import (
"fmt"
"unsafe"
)

type test struct {
a int
}

func main() {
arr := make([]C.ulong, 10)
t := test{}
C.setInt(unsafe.Pointer(&arr[0]))
C.setTest(unsafe.Pointer(&t))
fmt.Println(arr)
fmt.Println(t)
}
文章目录
  1. 1. 类型对应表
  2. 2. 例子
|