亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在C程序中使用golang函數

在C程序中使用golang函數

Go
當年話下 2023-07-04 14:55:06
我創建了一個golang程序來將一些值傳遞給c程序。?我的簡單 golang 代碼:package mainimport "C"func Add() int {? ? ? ? var a = 23? ? ? ? return a??}func main() {}然后我用它編譯了這個 go build -o test.so -buildmode=c-shared test.go我的C代碼:#include "test.h"int *http_200 = Add();?當我嘗試使用編譯它時gcc -o test test.c ./test.so我明白了int *http_200 = 添加(); ^ http_server.c:75:17:錯誤:初始值設定項元素不是常量為什么我會收到此錯誤?如何在我的 C 代碼中正確初始化該變量。PS:第一條評論后編輯。
查看完整描述

1 回答

?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

這里有幾個問題。首先是類型的不兼容。Go 將返回一個 GoInt。第二個問題是Add()必須導出該函數才能獲取所需的頭文件。如果您不想更改 Go 代碼,那么在 C 中您必須GoInt使用long long.


一個完整的例子是:


測試.go


package main


import "C"


//export Add

func Add() C.int {

    var a = 23

    return C.int(a)

}


func main() {}

測試.c


#include "test.h"

#include <stdio.h>


int main() {

    int number = Add();

    printf("%d\n", number);

}

然后編譯并運行:


go build -o test.so -buildmode=c-shared test.go

gcc -o test test.c ./test.so &&

./test

23


GoInt使用: test.go 的第二個示例


package main


import "C"


//export Add

func Add() int { // returns a GoInt (typedef long long GoInt)

    var a = 23

    return a

}


func main() {}

測試.c


#include "test.h"

#include <stdio.h>


int main() {

    long long number = Add();

    printf("%lld\n", number);

}

然后編譯并運行:


go build -o test.so -buildmode=c-shared test.go

gcc -o test test.c ./test.so &&

./test

23


查看完整回答
反對 回復 2023-07-04
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號