在C程序中使用golang函数

我创建了一个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 = 添加(); ^ http_server.c:75:17:错误:初始值设定项元素不是常量


为什么我会收到此错误?如何在我的 C 代码中正确初始化该变量。


PS:第一条评论后编辑。


当年话下
浏览 132回答 1
1回答

繁华开满天机

这里有几个问题。首先是类型的不兼容。Go 将返回一个 GoInt。第二个问题是Add()必须导出该函数才能获取所需的头文件。如果您不想更改 Go 代码,那么在 C 中您必须GoInt使用long long.一个完整的例子是:测试.gopackage mainimport "C"//export Addfunc Add() C.int {&nbsp; &nbsp; var a = 23&nbsp; &nbsp; return C.int(a)}func main() {}测试.c#include "test.h"#include <stdio.h>int main() {&nbsp; &nbsp; int number = Add();&nbsp; &nbsp; printf("%d\n", number);}然后编译并运行:go build -o test.so -buildmode=c-shared test.gogcc -o test test.c ./test.so &&./test23GoInt使用: test.go 的第二个示例package mainimport "C"//export Addfunc Add() int { // returns a GoInt (typedef long long GoInt)&nbsp; &nbsp; var a = 23&nbsp; &nbsp; return a}func main() {}测试.c#include "test.h"#include <stdio.h>int main() {&nbsp; &nbsp; long long number = Add();&nbsp; &nbsp; printf("%lld\n", number);}然后编译并运行:go build -o test.so -buildmode=c-shared test.gogcc -o test test.c ./test.so &&./test23
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go