Building a dll with Go 1.7

前端 未结 3 1810
生来不讨喜
生来不讨喜 2020-12-07 23:39

Is there a way to build a dll against Go v1.7 under Windows ?

I tried a classic

go build -buildmode=shared main.go

but get

3条回答
  •  佛祖请我去吃肉
    2020-12-08 00:15

    There is a project on github which shows how to create a DLL, based on, and thanks to user7155193's answer.

    Basically you use GCC to build the DLL from golang generated .a and .h files.

    First you make a simple Go file that exports a function (or more).

    package main
    
    import "C"
    import "fmt"
    
    //export PrintBye
    func PrintBye() {
        fmt.Println("From DLL: Bye!")
    }
    
    func main() {
        // Need a main function to make CGO compile package as C shared library
    }
    

    Compile it with:

    go build -buildmode=c-archive exportgo.go
    

    Then you make a C program (goDLL.c) which will link in the .h and .a files generated above

    #include 
    #include "exportgo.h"
    
    // force gcc to link in go runtime (may be a better solution than this)
    void dummy() {
        PrintBye();
    }
    
    int main() {
    
    }
    

    Compile/link the DLL with GCC:

    gcc -shared -pthread -o goDLL.dll goDLL.c exportgo.a -lWinMM -lntdll -lWS2_32
    

    The goDLL.dll then can be loaded into another C program, a freepascal/lazarus program, or your program of choice.

    The complete code with a lazarus/fpc project that loads the DLL is here: https://github.com/z505/goDLL

提交回复
热议问题