英文:
What methods are there currently that allow you to call a Go function in C?
问题
我看到了很多不同的方法可以实现这个,但是它们都不太理想,因为需要使用很多包装和回调函数。有没有一种简单的方法可以做到这一点?
例如,我们有以下代码:
//foo.go
package foo
import "C"
//export SayFive
func SayFive() int {
return 5
}
现在,这已经被简化到最小了,我只想在这一点上能够调用SayFive
函数。
然而,不是在这个文件的顶部。能够在C中这样做非常简单和有用,但是我正在寻找一种像这样的方法:
//foo.c
#include <stdio.h>
int main() {
int a = SayFive();
}
我在示例中看到过类似上面的代码,其中包括#include "_cgo_export.h"
,这是完全有道理的,但是当我这样做并尝试编译时,它失败了。
有人能解释一下涉及到的整个过程,让我们能够做到这一点吗?
英文:
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
得分: 4
你可以在Go中调用C,也可以在C中调用Go,但只能在Go程序的框架内进行。
所以你提到的带有main()
的C程序是行不通的,因为那样会在C程序的框架内调用Go。
换句话说,Go不能创建可以静态或动态链接到C程序的对象。
所以你需要改变思路,将Go程序作为主程序,从中调用C程序的部分。这意味着带有main()
函数的程序必须是一个Go程序。
希望这样说得清楚!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论