基础语法

  1. C语言代码需以注释形式编写;
  2. C语言代码块需要紧挨import "C" 语句上方; ```go package main

/**

include

//C语言函数格式 void Print() { printf(“hello word!”); } */ import “C”

func main() { C.Print() }

  1. <a name="ITjYL"></a>
  2. ### 类型转换
  3. ```go
  4. package main
  5. /*
  6. #include <stdio.h>
  7. //C语言函数格式
  8. int add(int a, int b)
  9. {
  10. return a + b;
  11. }
  12. */
  13. import "C"
  14. import "fmt"
  15. func main() {
  16. a := 10
  17. b := 20
  18. c := C.add(C.int(a), C.int(b)) // 将a和b从go语言的int类型转换成C语言的int类型
  19. fmt.Println(c)
  20. fmt.Printf("%T\n", c) //转成Go语言整型
  21. fmt.Println(int(c)) // 将c从C语言的int类型转换成go语言的int类型
  22. }

类型对照表

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