golang 编译为dll 的方法

本文详细介绍了如何使用Golang将程序编译为DLL动态链接库,包括安装MinGW、编写Go代码、编译及调用示例,展示了从Go到DLL的完整流程。

Golang封装成dll可以吗?要怎么做

Golang可以将程序编译成DLL文件,具体做法如下:

1、golang 编译 dll 过程中需要用到 gcc,所以先安装 MinGW。

windows 64 位系统应下载 MinGW 的 64 位版本: https://sourceforge.net/projects/mingw-w64/

2、下载后运行 mingw-w64-install.exe,完成 MingGW 的安装。

3、首先撰写 golang 程序 exportgo.go:

package main
import "C"
import "fmt"
//export PrintBye
func PrintBye() {
    fmt.Println("From DLL: Bye!")
}
//export Sum
func Sum(a int, b int) int {
    return a + b;
}
func main() {
    // Need a main function to make CGO compile package as C shared library
}

4、编译成 DLL 文件:

go build -buildmode=c-shared -o exportgo.dll exportgo.go

编译后得到 exportgo.dll 和 exportgo.h 两个文件。

5、参考 exportgo.h 文件中的函数定义,撰写 C# 文件 importgo.cs:

using System;
using System.Runtime.InteropServices;
namespace HelloWorld
{
    class Hello 
    {
        [DllImport("exportgo.dll", EntryPoint="PrintBye")]
        static extern void PrintBye();
        [DllImport("exportgo.dll", EntryPoint="Sum")]
        static extern int Sum(int a, int b);
        static void Main() 
        {
            Console.WriteLine("Hello World!");
            PrintBye();
            Console.WriteLine(Sum(33, 22));
        }
    }
}

编译 CS 文件得到 exe

csc importgo.cs

将 exe 和 dll 放在同一目录下,运行。

>importgo.exe
Hello World!
From DLL: Bye!
55

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值