c++ - Go 共享库作为 C++ 插件

标签 c++ go shared-libraries

我有一个项目,我想在 C++ 应用程序中加载 Go 插件。

经过大量研究,我不清楚 Go 是否支持这个。 我遇到了很多指出动态链接的坏习惯的讨论,而不是使用 IPC。此外,我不清楚动态链接是否是语言的意图(新的 Go 哲学?)。

cgo 提供了从 Go 调用 C 或从 C(在 Go 内部)调用 Go 的能力,但不能从普通的旧 C 调用。或者是吗?

显然上游也发生了一些事情(https://codereview.appspot.com/7304104/)

ma​​in.c

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

int main() {
        Print();
}

打印.go

package main

import "fmt"

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

生成文件:

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

输出:

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

有解决办法吗?什么是最好的方法? fork + IPC?

引用:

最佳答案

我不认为你可以将 Go 嵌入到 C 中。但是你可以将 C 嵌入到 Go 中,并且使用一个小的 stub C 程序你可以首先调用 C,这是下一个最好的事情! Cgo 绝对支持与共享库的链接,所以也许这种方法适合你。

像这样

ma​​in.go

// Stub go program to call cmain() in C
package main

// extern int cmain(void);
import "C"

func main() {
     C.cmain()
}

ma​​in.c

#include <stdio.h>

// Defined in Go
extern void Print(void);

// C Main program
int cmain() {
  printf("Hello from C\n");
  Print();
}

打印.go

package main

import "fmt"

import "C"

//export Print
func Print() {
    fmt.Printf("Hello from Go\n")
}

使用 go build 编译,并在运行时生成此输出

Hello from C
Hello from Go

关于c++ - Go 共享库作为 C++ 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16806060/

相关文章:

go - 多包go模块中的名称解析问题

windows - 戈朗 : winapi call with struct parameter

go - 为什么我的 Rust 程序比执行相同的按位和 I/O 操作的 Go 程序慢 4 倍?

使用 mhash 编译程序

android - 当使用最新的 Android NDK NativeActivity 垃圾邮件来记录触摸事件时

c++ - Boost.Spirit 表达式未找到重载输出运算符

c++ - Main.cpp 无法访问头文件和其他 .cpp 文件中的变量和函数

c++ - 适当使用 friend ?容器类旨在操纵特定类型的对象

c++ - 包含 C 文件/与 CMake 的链接不适用于 C++ : cannot include function

linux - 为什么没有更多地使用静态链接?