Golang能封装成dll吗

Golang能封装成dll吗,第1张

Golang能封装成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

更多golang知识请关注PHP中文网golang教程栏目。

以上就是Golang能封装成dll吗的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/684947.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存