在C程序中使用golang函数
我创建了一个在C程序中使用golang函数,c,go,cgo,C,Go,Cgo,我创建了一个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(); 当我尝试使用
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中,您必须使用GoInt
,这是一个long
一个完整的例子是:
测试。开始
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);
}
#include "test.h"
#include <stdio.h>
int main() {
long long number = Add();
printf("%lld\n", number);
}
二十三
第二个示例使用了GoInt
:
测试。开始
package main
import "C"
//export Add
func Add() C.int {
var a = 23
return C.int(a)
}
func main() {}
主程序包
输入“C”
//导出添加
func Add()int{//返回一个GoInt(typedef long GoInt)
变量a=23
归还
}
func main(){}
test.c
#include "test.h"
#include <stdio.h>
int main() {
int number = Add();
printf("%d\n", number);
}
#include "test.h"
#include <stdio.h>
int main() {
long long number = Add();
printf("%lld\n", number);
}
二十三
Go函数Add
返回一个普通的int
值。在C代码中,您将该值指定给指向int
的指针?请尝试制作一个C程序,复制粘贴完整的生成输出,并告诉我们您是如何生成的。谢谢,这是我想知道的。