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 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图