本文摘自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() {
}
|
编译
阅读剩余部分
相关阅读 >>
linux怎么安装golang和dep(附错两个误解决方法)
golang如何封装路由
chan(rutime. hchan)结构
go语言不可比较类型与map问题
golang 浮点类型、字符类型
golang 能不能打包为 dll ?
go的垃圾回收机制(gc)
关于golang channel的实现
golang项目如何部署到linux服务器
详解golang编译成dll文件
更多相关阅读请进入《golang》频道 >>
老貘
一个与时俱进的Go编程知识库。
转载请注明出处:木庄网络博客 » 详解Golang编译成DLL文件