>  기사  >  백엔드 개발  >  DLL 파일로 컴파일된 Golang에 대한 자세한 설명

DLL 파일로 컴파일된 Golang에 대한 자세한 설명

藏色散人
藏色散人앞으로
2020-12-31 15:06:444316검색

다음 golang 튜토리얼 칼럼에서는 Golang을 DLL 파일로 컴파일하는 방법을 소개하겠습니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

Golang은 dll 컴파일 시 gcc가 필요하므로 MinGW를 먼저 설치하세요.

Windows 64비트 시스템은 64비트 버전의 MinGW를 다운로드해야 합니다: https://sourceforge.net/projects/mingw-w64/

다운로드 후 mingw-w64-install.exe를 실행하여 MingGW 설치를 완료하세요. .

먼저 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

golang의 문자열 매개변수는 C#에서 다음과 같이 참조될 수 있습니다:

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;
    }
// func.go
package main

import "C"
import "fmt"

//export Add
func Add(a C.int, b C.int) C.int {
	return a + b
}

//export Print
func Print(s *C.char) {  
/* 
函数参数可以用 string, 但是用*C.char更通用一些。
由于string的数据结构,是可以被其它go程序调用的,
但其它语言(如 python)就不行了
*/
	print("Hello ", C.GoString(s)) //这里不能用fmt包,会报错,调了很久...
}
func main() {	
}                                                                                                                                        

Compile

go build -ldflags "-s -w" -buildmode=c-shared -o func.dll func.go
880KB로 여전히 약간 큽니다. 순수 C 컴파일은 48KB에 불과하며 아마도 모든 종속성을 포함하지 않을 것입니다. go가 완전히 포함되어 있습니다

Go 호출

package main
import (
	"fmt"
	"syscall"
)

func main() {
	dll := syscall.NewLazyDLL("func.dll")
	add := dll.NewProc("Add")
	prt := dll.NewProc("Print")
	r, err, msg := add.Call(32, 44)
	fmt.Println(r)
	fmt.Println(err)
	fmt.Println(msg)
	
	name := C.CString("Andy")
	prt.Call(uintptr(unsafe.Pointer(name)))
}
out:
76
0
The operation completed successfully.
Hello Andy

Python 호출

from ctypes import CDLL, c_char_p
dll = CDLL("func.dll")
dll.Add(32, 33)
dll.Print(c_char_p(bytes("Andy", "utf8")))

C++ 호출

#include <iostream>
#include <windows.h>

using namespace std;
typedef int(*pAdd)(int a, int b);
typedef void(*pPrt)(char* s);

int main(int argc, char *argv[])
{
    HMODULE dll= LoadLibraryA("func.dll");
    pAdd add = (pAdd)GetProcAddress(dll, "Add");
    pPrt prt = (pPrt)GetProcAddress(dll, "Print");
    cout << add(321, 33) << endl;
    prt("Andy");
    FreeLibrary(dll);
    return 0;
}

더 많은 관련 기술 기사를 보려면 go 언어 튜토리얼 칼럼을 방문하세요!

위 내용은 DLL 파일로 컴파일된 Golang에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제