未定义:Windows 10上的syscall.Mmap

I have this function in my Go project and I am getting the error as:

undefined syscall.Mmap

func memMap(fd uintptr, base int64) (mem []uint32, mem8 []byte, err error) {
    mem8, err = syscall.Mmap(
        int(fd),
        base,
        memLength,
        syscall.PROT_READ|syscall.PROT_WRITE,
        syscall.MAP_SHARED,
    )
    if err != nil {
        return
    }
    // Convert mapped byte memory to unsafe []uint32 pointer, adjust length as needed
    header := *(*reflect.SliceHeader)(unsafe.Pointer(&mem8))
    header.Len /= (32 / 8) // (32 bit = 4 bytes)
    header.Cap /= (32 / 8)
    mem = *(*[]uint32)(unsafe.Pointer(&header))
    return
}

The problem

Windows does not have the mmap(2) syscall—it's POSIX-specific (just in case: what "POSIX" is).

Windows has MapViewOfFile() and friends.

Solutions

There are two approaches, I reckon:

  • Use a "wrapper" package such as golang.org/x/exp/mmap which tries to provide a generic memory-mapping API which is cross-platform (that is, on POSIX platforms it will use mmap(2) and on Windows is will use Windows-specific API).

  • Use the appropriate Win32 API functions directly instead of syscall.Mmap.

    Should you take this route, the golang.org/x/sys/windows package has the relevant functions readily available.

A third approach is to have your own custom implementation working with memory-mapped data which calls either syscall.Mmap and friends of Windows-specific API. Such implementation should supposedly involve using so-called build constraints to conditionally compile a particular target platform-specific implementation—just like golang.org/x/exp/mmap does.