dongliang1941 2013-05-29 05:21
浏览 64
已采纳

将共享库作为C ++插件

I have a project where I would like to load Go plugins inside a C++ application.

After a lot of research, it is not clear for me whether or not Go supports this. I encountered a lot of discussions pointing out the bad habit of dynamic linking, proning IPC instead. Moreover it is not clear for me if dynamic linking is intended by the language or not (new Go philosophy ?).

cgo provides the ability to call C from Go or Go from C (inside Go), but not from plain old C. Or does it ?

  • gc doesn't seem to support shared library (even if https://code.google.com/p/go/issues/detail?id=256 mentions it does)
  • gccgo support Go shared libraries but I couldn't make it work (probably because the main entry point is not in Go ...)
  • SWIG doesn't seem to help either :(

Apparently something is going on upstream as well (https://codereview.appspot.com/7304104/)

main.c

extern void Print(void) __asm__ ("example.main.Print");

int main() {
        Print();
}

print.go

package main

import "fmt"

func Print() {
    fmt.Printf("hello, world
")
}

Makefile :

all: print.o main.c
        gcc main.c -L. -lprint -o main

print.o: print.go
        gccgo -fno-split-stack -fgo-prefix=example -fPIC -c print.go -o print.o
        gccgo -shared print.o -o libprint.so

Output :

/usr/lib/libgo.so.3: undefined reference to `main.main'
/usr/lib/libgo.so.3: undefined reference to `__go_init_main'

Is there a solution for that ? What is the best approach ? forking + IPC ?

References :

  • 写回答

2条回答 默认 最新

  • douzhun5971 2013-05-29 06:28
    关注

    I don't think you can embed Go into C. However you can embed C into Go and with a little stub C program you can call into C first thing which is the next best thing! Cgo definitely supports linking with shared libraries so maybe this approach will work for you.

    Like this

    main.go

    // Stub go program to call cmain() in C
    package main
    
    // extern int cmain(void);
    import "C"
    
    func main() {
         C.cmain()
    }
    

    main.c

    #include <stdio.h>
    
    // Defined in Go
    extern void Print(void);
    
    // C Main program
    int cmain() {
      printf("Hello from C
    ");
      Print();
    }
    

    print.go

    package main
    
    import "fmt"
    
    import "C"
    
    //export Print
    func Print() {
        fmt.Printf("Hello from Go
    ")
    }
    

    Compile with go build, and produces this output when you run it

    Hello from C
    Hello from Go
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了