为了账号安全,请及时绑定邮箱和手机立即绑定

在C程序中使用golang函数

在C程序中使用golang函数

Go
当年话下 2023-07-04 14:55:06
我创建了一个golang程序来将一些值传递给c程序。 我的简单 golang 代码:package mainimport "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:第一条评论后编辑。
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

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


一个完整的例子是:


测试.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


查看完整回答
反对 回复 2023-07-04
  • 1 回答
  • 0 关注
  • 130 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号