本文摘自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() {
}
|
编译
阅读剩余部分
相关阅读 >>
手撸golang 架构设计原则 里氏替换原则
19 golang包以及go mod
golang 创建型设计模式 建造者模式
go-carbon 1.3.1 版本发布,新增 diffforhumans() 方法和多语言支持
redis go语言与redis数据库交互
golang判断js文件是否存在
golang iota从几开始
golang 可以把包名去掉吗?
使用golang 做复杂流程自动化
golang 和 php 哪个性能更强?
更多相关阅读请进入《golang》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » 详解Golang编译成DLL文件