Home >Backend Development >Golang >Can Golang be packaged into a dll?

Can Golang be packaged into a dll?

angryTom
angryTomOriginal
2020-03-17 16:09:184397browse

Can Golang be packaged into a dll?

Can Golang be packaged into a dll?

Golang can compile a program into a DLL file. The specific method is as follows:

1. Golang needs to use gcc when compiling dll, so install MinGW first.

Windows 64-bit system should download the 64-bit version of MinGW: https://sourceforge.net/projects/mingw-w64/

2. After downloading, run mingw-w64-install.exe , complete the installation of MingGW.

(Recommended learning: Website Construction Tutorial)

3. First write the golang program 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
}

4. Compile it into a DLL file:

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

After compilation, we get two files exportgo.dll and exportgo.h.

5. Refer to the function definition in the exportgo.h file and write the C# file 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));
        }

Compile the CS file to get exe

csc importgo.cs

Put the exe and dll in In the same directory, run.

>importgo.exe
Hello World!
From DLL: Bye!
55

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of Can Golang be packaged into a dll?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn