簡體   English   中英

在C程序中使用golang函數

[英]Use golang function inside C-program

我創建了一個golang程序來將一些值傳遞給c程序。 我用這個例子來做到這一點

我簡單的golang代碼:

package main

import "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 = Add(); ^ http_server.c:75:17:錯誤:初始化元素不是常量

為什么我收到此錯誤? 如何在我的C代碼中正確初始化該變量。

PS:在第一次評論后編輯。

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

一個完整的例子是:

test.go

package main

import "C"

//export Add
func Add() C.int {
    var a = 23
    return C.int(a)
}

func main() {}

test.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() {}

test.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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM