將Go 程式碼整合到現有的C 專案中
問題:
是否可以呼叫Go代碼來自 C程序,如果是這樣,這怎麼可能
答案:
是的,Go 1.5 引入了-buildmode=c-archive 模式,該模式允許將Go 程式碼編譯成適合連結到C 程式的存檔。要將Go 程式碼整合到現有的C 專案中:
標記要匯出的函數:
編譯去存檔:
使用以下指令將 Go 程式碼編譯為 C>
go build -buildmode=c-archive foo.go使用下列指令將 Go 程式碼編譯為可呼叫靜態函式庫:
連結 C程式:
#include "foo.h"在C 程式中,包含產生的頭檔:
gcc -pthread foo.c foo.a -o foo連結使用-pthread 選項針對Go檔案:
範例:
package main import "C" import "fmt" //export PrintInt func PrintInt(x int) { fmt.Println(x) } func main() {}考慮下列Go 程式碼(foo.go):go build -buildmode=c-archive foo.go然後,在C 程式(foo.c) 中:
#include "foo.h" int main(int argc, char **argv) { PrintInt(42); return 0; }編譯它:
gcc -pthread foo.c foo.a -o foo運行 foo 將列印「42」。
以上是如何將 Go 程式碼整合到我現有的 C 專案中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!