本文摘自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"
func PrintBye() {
fmt.Println( "From DLL: Bye!" )
}
func Sum(a int, b int) int {
return a + b;
}
func main() {
}
|
编译成 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
将 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 | package main
import "C"
import "fmt"
func Add(a C.int, b C.int) C.int {
return a + b
}
func Print (s *C.char) {
print ( "Hello " , C.GoString(s))
}
func main() {
}
|
编译
阅读剩余部分
相关阅读 >>
[系列] go - chan 通道
golang语言学习之基本语法
go module访问私有git仓库
ssh连接服务器后执行多条命令
go time 包中的 adddate 的逻辑避坑指南
使用viper读取nacos配置(开源)
golang在各平台下交叉编译
golang返回错误时如何正确处理
聊聊dubbo-go-proxy的consulregistryload
关于golang select典型用法
更多相关阅读请进入《golang》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » 详解Golang编译成DLL文件