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?

有帮助吗?

解决方案

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!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top