[转载]Golang 编译成 DLL 文件

时间:2022-05-04
本文章向大家介绍[转载]Golang 编译成 DLL 文件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先撰写 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
}

编译成 DLL 文件:

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

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

参考 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