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条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP