user140053
user140053

Reputation:

Building a dll with Go 1.7

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

-buildmode=shared not supported on windows/amd64

update Ok, I've got my answer. For those who are interested : https://groups.google.com/forum/#!topic/golang-dev/ckFZAZbnjzU

Upvotes: 25

Views: 53258

Answers (4)

binarytrails
binarytrails

Reputation: 655

Just tested on Windows 10 and this works perfectly:

> go version                                                                                     
go version go1.17.2 windows/amd64

> cat main.go
package main

import (
  "C"
)

//export Entry
func Entry(){
  main()
}

func main() {
  // do something
}

> go build -buildmode=c-shared -o mydll.dll main.go
> dumpbin /EXPORTS mydll.dll 
File Type: DLL
..
    ordinal hint RVA      name

          1    0 ...      Entry

> rundll32.exe .\mydll.dll,Entry

Upvotes: 1

Andrew Dolder
Andrew Dolder

Reputation: 406

As of Go 1.10, -buildmode=c-shared is now supported on Windows.

Release notes: https://golang.org/doc/go1.10#compiler

So now compiling to DLL is a one-liner:

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

I believe the headers are only compatible with GCC. If you're only exposing C-types, this should not be a big issue. I was able to get LoadLibrary to work in Visual Studio without the header.

Upvotes: 29

Another Prog
Another Prog

Reputation: 849

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 <stdio.h>
#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

Upvotes: 13

user7155193
user7155193

Reputation: 221

go build -buildmode=c-archive github.com/user/ExportHello

====> will build ExportHello.a, ExportHello.h

Take the functions built in ExportHello.a and re-export in Hello2.c

gcc -shared -pthread -o Hello2.dll Hello2.c ExportHello.a -lWinMM -lntdll -lWS2_32

====> will generate Hello2.dll

Upvotes: 22

Related Questions