温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-04-28 14:53:19 来源:亿速云 阅读:1919 作者:小新 栏目:编程语言

Golang封装成dll可以吗?要怎么做?可能有的人对Golang并不陌生,或者从来没有了解过Golang。但是不用担心,今天小编会以最简单的描述来讲解Golang的原理,告诉大家Golang如何封装成dll。

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封装成dll可以吗?要怎么做的详细内容了,看完之后是否有所收获呢?如果如果想了解更多,欢迎来亿速云行业资讯!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI