天天看點

CGO程式設計

1)什麼是CGO程式設計?

2)CGO文法

3)相關資料

一、什麼是CGO程式設計?

簡單說就是GO語言代碼中可以編寫C代碼和調用C代碼,在一些偏底層業務中,用C來編寫會比較簡單,然後GO中來調用

二、CGO文法

1)簡單案例

2)GO與C語言類型轉換

3)GO語言傳值到C語言

(1)簡單案例

package main
/*
#include <stdio.h>
int a = 1;
char s[30] = "12345";
int fun1() {
    printf("hello cgo!\n");
}
 */
import "C"
import "fmt"

func main() {
    fmt.Println(C.a)
    fmt.Println(C.s)
    C.fun1()
}

輸出結果:
1
[49 50 51 52 53 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
hello cgo!
           

C代碼在GO語言中嵌入在/**/内,然後引入C代碼,必須在緊接的下一行,不能有空行或其他代碼,否則不能引入

/*
C代碼
*/
import "C"
           

然後GO中調用C代碼的話,以C. + 變量名或函數名

(2)GO與C語言類型轉換

GO調用列印C變量類型:

package main
/*
#include <stdio.h>
int a = 1;
float f = 1.2;
double d = 1.3;
char c = '1';
char s[30] = "12345";
 */
import "C"
import "fmt"

func main() {
    fmt.Printf("int      %T\n", C.a)
    fmt.Printf("char     %T\n", C.c)
    fmt.Printf("char[30] %T\n", C.s)
    fmt.Printf("float    %T\n", C.f)
    fmt.Printf("double   %T\n", C.d)
}

輸出:
int      main._Ctype_int
char     main._Ctype_char
char[30] [30]main._Ctype_char
float    main._Ctype_float
double   main._Ctype_double
           

C -> GO

int,float,double,char類型變量可以直接強轉

// 轉換 C 字元串到 Golang 字元串
func C.GoString(*C.char) string

// 轉換一定長度的 C 字元串到 Golang 字元串
func C.GoStringN(*C.char, C.int) string

// 對于C字元串數組變量,沒有辦法直接用C.GoString()和C.GoStringN()直接轉換,可以使用chart*替代字元串數組變量的使用
           

GO -> C

對于int,float,double,char可以直接強轉指派
char*使用C.CString()
           
package main
/*
#include <stdio.h>
int a = 1;
float f = 1.2;
double d = 1.3;
char c = '1';
char* s = "12345";
int fun1(int a, char c, float f, double d,char *s) {
    printf("%d %c %f %f %s\n", a, c, f, d, s);
}
 */
import "C"

func main() {
    C.fun1(1, 'a', 1.2, 1.5, C.CString("dsadsad"))
}
           

三、相關資料

1)

https://www.kancloud.cn/wizardforcel/gopl-zh/106479

2)

https://studygolang.com/articles/8106

3)

https://studygolang.com/articles/3190

繼續閱讀