我创建了一个 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 将返回一个 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() {}
测试.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
关于c - 在 C 程序中使用 golang 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57002881/