dongri1989 2014-04-19 11:09
浏览 66
已采纳

当前有哪些方法可以让您在C语言中调用Go函数?

I've seen lots of different ways this can be done, none of them seem ideal in terms of having to use lots of wrappers and callbacks. Is there a simple way of doing this?

For example, we have this:

//foo.go

package foo

import "C"

//export SayFive
func SayFive() int {
    return 5
}

This has been stripped down to the minimum now, and all I want to be able to do at this point is call that SayFive function in C.

However, not at the top of this file. It's very simple and useful to be able to do that, but I'm looking for a way like this:

//foo.c

#include <stdio.h>

int main() {
    int a = SayFive();
}

I've seen in examples that are like the above, that #include "_cgo_export.h" which makes total sense, but when I've done that and tried to compile it, it fails.

Could anyone explain the whole process involved that would allow us to do this?

  • 写回答

1条回答 默认 最新

  • douzong0711 2014-04-19 11:55
    关注

    You can call C from Go and Go from C, but only within the framework of a Go program.

    So your example of a C program with a main() won't work, because that would be calling Go from within the framework of a C program.

    In other words, Go can't make objects you can link statically or dynamically with C programs.

    So you'll have to turn what you want to do on its head and make the Go program the master, and call the C program parts from it. That means the program with the main() function must be a Go program.

    Hope that makes sense!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器