详解Golang编译成DLL文件


本文摘自php中文网,作者藏色散人,侵删。

下面由golang教程栏目给大家介绍Golang 编译成 DLL 文件 的方法,希望对需要的朋友有所帮助!

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

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

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

首先撰写 golang 程序 exportgo.go:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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

}

编译成 DLL 文件:

1

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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

1

csc importgo.cs

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

1

2

3

4

5

>importgo.exe

 

Hello World!

From DLL: Bye!

55

golang 中的 string 参数在 C# 中可以如下引用:

1

2

3

4

5

6

7

8

9

10

11

12

public struct GoString

    {

        public string Value { get; set; }

        public int Length { get; set; }

 

        public static implicit operator GoString(string s)

        {

            return new GoString() { Value = s, Length = s.Length };

        }

 

        public static implicit operator string(GoString s) => s.Value;

    }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// func.go

package main

 

import "C"

import "fmt"

 

//export Add

func Add(a C.int, b C.int) C.int {

    return a + b

}

 

//export Print

func Print(s *C.char) { 

/*

函数参数可以用 string, 但是用*C.char更通用一些。

由于string的数据结构,是可以被其它go程序调用的,

但其它语言(如 python)就不行了

*/

    print("Hello ", C.GoString(s)) //这里不能用fmt包,会报错,调了很久...

}

func main() {  

}                                                                                                                                        

编译

阅读剩余部分

相关阅读 >>

[系列] go - chan 通道

golang语言学习之基本语法

go module访问私有git仓库

ssh连接服务器后执行多条命令

go time 包中的 adddate 的逻辑避坑指南

使用viper读取nacos配置(开源)

golang在各平台下交叉编译

golang返回错误时如何正确处理

聊聊dubbo-go-proxy的consulregistryload

关于golang select典型用法

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...