drmy1050 2015-03-15 03:07
浏览 70
已采纳

如何在C的多个程序包中重用Go回调?

Is there a way to build a Go + C application that:

  • From main package X, import packages Y and Z.
  • Package M exports a go callback F.
  • Packages X and Y are both built with accompanying C files, both want to call F from C source code.

Generally speaking I'm trying to figure out how to call a callback from accompanying C files in other modules which are used to build a final application. I coudn't figure out how to achieve this or something similar. I'm also interested in convoluted solutions.

  • 写回答

3条回答 默认 最新

  • dquh37673 2015-03-22 15:46
    关注

    I don't see a way to call a Go function across packages, but all cgo packages are linked into the same binary and can call each other. This means that you can export M.F to a C function in package M and call that C function from packages Y and Z.

    m/m.go:

    package m
    
    // void F();
    import "C"
    import "fmt"
    
    //export F
    func F() {
        fmt.Println("m.f")
    }
    

    m/m.h:

    void m_f();
    

    m/m.c:

    #include <stdio.h>
    #include "_cgo_export.h"
    #include "m.h"
    
    void m_f() {
        printf("m_f
    ")
        F();
    }
    

    y/y.go:

    package y
    
    // The LDFLAGS lines below are needed to prevent linker errors
    // since not all packages are present while building intermediate
    // packages. The darwin build tag is used as a proxy for clang
    // versus gcc because there doesn't seem to be a better way
    // to detect this.
    
    // #cgo darwin LDFLAGS: -Wl,-undefined -Wl,dynamic_lookup
    // #cgo !darwin LDFLAGS: -Wl,-unresolved-symbols=ignore-all
    // #include "y.h"
    import "C"
    
    import (
        "fmt"
        _ "m"
    )
    
    func Y() {
        fmt.Println("y.Y")
        C.y()
    }
    

    y/y.h:

    void y();
    

    y/y.c:

    #include <stdio.h>
    #include "../m/m.h"
    
    void y() {
        printf("y.C.y
    ");
        m_f();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?