Golang代码能否编译成.lib/dll/so以便在CPP中使用?

Golang代码能否编译成.lib/dll/so以便在CPP中使用? 是否可以将Go代码编译成.lib/dll/so文件,以便在C++中使用?

3 回复

非常感谢您的回复!

我会进一步研究cgo,如果有任何新发现会更新这篇帖子。

此致,

更多关于Golang代码能否编译成.lib/dll/so以便在CPP中使用?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


既是也不是。Go语言提供了"c-archive"和"c-shared"这两种构建模式,可以构建供C语言使用的静态库和动态库。不过据我所知,目前仅支持linux-amd64和darwin-amd64平台。这里是在Google上搜到的第一篇相关文章,展示了如何使用这些构建模式(虽然文章来自2015年,某些细节可能已有所改变):

http://blog.ralch.com/tutorial/golang-sharing-libraries/

是的,可以将Go代码编译成共享库(如Windows上的.dll、Linux上的.so或macOS上的.dylib),以便在C++中使用。这需要使用Go的-buildmode=c-shared标志。以下是具体方法和示例。

步骤:

  1. 编写Go代码:使用//export注释导出函数,并导入C包。
  2. 编译为共享库:使用go build -buildmode=c-shared -o <output> <source>命令。
  3. 在C++中使用:通过头文件声明和链接共享库调用函数。

示例:

1. Go代码(example.go):

package main

import "C"

//export Add
func Add(a, b int) int {
    return a + b
}

//export Greet
func Greet(name *C.char) *C.char {
    return C.CString("Hello, " + C.GoString(name))
}

func main() {
    // 必需:空main函数
}

注意:导出的函数必须使用//export注释,且包必须为main

2. 编译共享库:

  • Windows
    go build -buildmode=c-shared -o example.dll example.go
    
    同时生成example.dllexample.h
  • Linux/macOS
    go build -buildmode=c-shared -o example.so example.go
    
    生成example.soexample.h

3. C++代码(main.cpp):

使用生成的头文件和共享库:

#include <iostream>
#include "example.h"  // 自动生成的头文件

int main() {
    // 调用Add函数
    int result = Add(3, 4);
    std::cout << "Add result: " << result << std::endl;

    // 调用Greet函数
    char* msg = Greet("World");
    std::cout << "Greeting: " << msg << std::endl;
    // 释放Go返回的字符串内存
    free(msg);

    return 0;
}

4. 编译和链接C++代码:

  • Windows(使用MinGW或Visual Studio)
    g++ -o main main.cpp -L. -lexample
    
  • Linux/macOS
    g++ -o main main.cpp -L. -lexample -Wl,-rpath,.
    

注意事项:

  • 内存管理:Go返回的字符串需在C++中用free释放,因为Go使用自己的分配器。
  • 类型映射:Go的int对应C的long,字符串使用*C.char
  • 依赖:共享库可能依赖其他动态库,部署时需确保环境一致。

通过以上步骤,Go函数可以在C++中直接调用,实现跨语言互操作。

回到顶部