go-doc-cgo

介绍

  • 类型对照表
C语言类型 CGO类型 Go语言类型
char C.char byte
singed char C.schar int8
unsigned char C.uchar uint8
short C.short int16
unsigned short C.ushort uint16
int C.int int32
unsigned int C.uint uint32
long C.long int32
unsigned long C.ulong uint32
long long int C.longlong int64
unsigned long long int C.ulonglong uint64
float C.float float32
double C.double float64
size_t C.size_t uint

示例

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"fmt"
"syscall"
"unsafe"
)


/*
#include <stdio.h>
#include <string.h>

struct CReq {
char str1[32];
int i1;
float f1;
};

struct CRes {
char str1[32];
int i1;
float f1;
};

void TestStrcpy(char *s1, char *s2) {
strcpy(s2, "TestStrcpy");
printf("TestStrcpy 函数调用:%s\n", s1);
}

void TestStruct1(struct CReq *req, struct CRes *res) {
printf("TestStruct1 函数调用:%s %d %f \n", req->str1, req->i1, req->f1);

strcpy(res->str1, "TestStruct1");
res->i1 ++;
res->f1 ++;
//printf("%s \n\n", res->str1);
}

*/
import "C"

func main() {

// 字符串
var s2 [10]byte
s1 := []byte("TestStrcpy 111")

C.TestStrcpy((*C.char)(unsafe.Pointer(&s1[0])), (*C.char)(unsafe.Pointer(&s2[0])))
fmt.Println("TestStrcpy 函数调用结果", string(s2[:]))

// 结构体
var req C.struct_CReq
//str1 := C.CString("会画画111")
//req.str1 = unsafe.Pointer(str1)
req.i1 = C.int(1)
req.f1 = C.float(1.1)

reqBs := []byte("李克强文")
for i, v := range reqBs {
req.str1[i] = C.char(v)
}

var res C.struct_CRes
res.i1 = C.int(1)
res.f1 = C.float(1.1)
C.TestStruct1(&req, &res)

bs := make([]byte, 32)
for i := 0; i < 32; i++ {
bs[i] = byte(res.str1[i])
}

fmt.Println("TestStruct1 函数调用结果:", string(bs), res.i1, res.f1)


//var dirs [4][16]byte
dirs := make([][]byte, 4)
for i := 0; i < 4; i++ {
dirs[i] = make([]byte, 16)
}
}