Skip to content

Calling Windows API from Go

Hanjun Kim edited this page Feb 24, 2019 · 19 revisions

Calling Windows API from Go is pretty simple and straightforward as documented in official repository. So what I'm gonna list here are just some additional information about it.

Should I use syscall, or golang.org/x/sys/windows?

it's recommended to use golang.org/x/sys/windows instead of standard syscall if possible:

Yes, you should switch to x/sys. Some things crept into syscall under the covers, others went in because it's the job of that package to support the main repo and changes were required. But external packages should be using x/sys.

- Rob Pike from Google Groups

You can see there are lots of Windows APIs already defined in golang.org/x/sys/windows. If you're gonna use only those Windows APIs listed there, it's fine and encouraged to just use them. But if you find you need other APIs that are not listed there, you should define it by your hands.

ANSI and Unicode versions of Windows API

If a Windows API takes string as its parameter, there are two different versions of same API. As you probably know, ANSI and Unicode versions. Strings in Go are basically unicode strings, so we'd use Unicode version of Windows API that has W prefix(e.g. MessageBoxW) most of the time.

Windows Data Types

I recommend you to have Windows Data Types link in your bookmark bar. It's really helpful in situations like, when you get stuck wondering what LGRPID type is.

For common data types that can be found on frequently used Windows APIs, I wrote a list of corresponding data type in Go. See Data Type Cheat Sheet for details.

Defining Windows API by Hands

First of all, let's call MessageBoxW from Go.