What methods are there currently that allow you to call a Go function in C?

huangapple go评论89阅读模式
英文:

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 &quot;C&quot;

//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 &lt;stdio.h&gt;

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

I've seen in examples that are like the above, that #include &quot;_cgo_export.h&quot; 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!

huangapple
  • 本文由 发表于 2014年4月19日 19:09:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/23169238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定