C語言調用GO

C語言調用GO

最近工做中遇到須要在c語言裏面調用go語言的需求,總結了一下,下面代碼裏面的每個註釋都頗有用,閒話很少說,直接上代碼~函數

示例

GO代碼:ui

package main // 這個文件必定要在main包下面

import "C" // 這個 import 也是必須的,有了這個才能生成 .h 文件
// 下面這一行不是註釋,是導出爲SO庫的標準寫法,注意 export前面不能有空格!!!
//export hello
func hello(value string)*C.char { // 若是函數有返回值,則要將返回值轉換爲C語言對應的類型
    return C.CString("hello" + value)
}
func main(){
    // 此處必定要有main函數,有main函數才能讓cgo編譯器去把包編譯成C的庫
}

注:若是go函數有多個返回值,會生成一個struct,在寫c代碼時要用相應的struct接收,參照生成的.h文件code

生成so庫
go build -buildmode=c-shared -o hello.so hello.go編譯器

C代碼:string

#include <stdio.h>
#include <string.h>
#include "hello.h" // 此處爲上一步生成的.h文件

int main(){
    char c1[] = "did";
    GoString s1 = {c1,strlen(c1)};// 構建go類型
    char *c = hello(s1);
    printf("r:%s",c);
    return 0;
}

編譯C代碼
gcc -o c_go test.c hello.so
注:這裏要把以前生成的so文件已寫在後面io

最後執行:
./c_go編譯

相關文章
相關標籤/搜索