在 C 程序中使用 golang 函数

Use golang function inside C-program

我创建了一个 golang 程序来将一些值传递给 c 程序。 I used this example to do so

我简单的 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: error: initializer element is not constant

为什么会出现这个错误?如何在我的 C 代码中正确初始化该变量。

PS : 在第一条评论后编辑。

这里有几个问题。首先是类型的不兼容。 Go 将 return 一个 GoInt。第二个问题是必须导出 Add() 函数以获得所需的头文件。如果你不想改变你的 Go 代码,那么在 C 中你必须使用 GoInt 这是一个 long long.

一个完整的例子是:

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