基础语法
- C语言代码需以注释形式编写;
- C语言代码块需要紧挨
import "C"
语句上方; ```go package main
/**
include
//C语言函数格式 void Print() { printf(“hello word!”); } */ import “C”
func main() { C.Print() }
<a name="ITjYL"></a>
### 类型转换
```go
package main
/*
#include <stdio.h>
//C语言函数格式
int add(int a, int b)
{
return a + b;
}
*/
import "C"
import "fmt"
func main() {
a := 10
b := 20
c := C.add(C.int(a), C.int(b)) // 将a和b从go语言的int类型转换成C语言的int类型
fmt.Println(c)
fmt.Printf("%T\n", c) //转成Go语言整型
fmt.Println(int(c)) // 将c从C语言的int类型转换成go语言的int类型
}
类型对照表
C语言类型 | CGO类型 | Go语言类型 |
---|---|---|
char | C.char | byte |
singed char | C.schar | int8 |
unsigned char | C.uchar | uint8 |
short | C.short | int16 |
unsigned short | C.short | 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 | flfloat64 |
size_t | C.size_t | uint |