2014-04-19 11:09
浏览 65


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:


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:


#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!

    解决 无用
    打赏 举报

相关推荐 更多相似问题