简体   繁体   中英

Running Windows API functions from WSL

I was wondering if there is a way to run Windows API functions from WSL1 or WSL2. It sounds unlikely in WSL2 since it uses Hypervisor and not aware to the Windows environment, but maybe using WSL1?

If you are asking whether you can "mix and match" the Windows API into a Linux ELF binary, then not directly, but see below for a workaround (which may be what you are looking for anyway).

Windows executables using the Windows API will run just fine under both WSL1 and WSL2. To quote from this SU answer , this works because:

The Windows executable (PE binary) is added as a binfmt_misc entry in WSL2. In simple words, binfmt_misc is a Linux kernel feature which allows arbitrary executable file formats to be recognized and passed to certain programs.

Note that you do need to specify the .exe for a Windows binary to run. For instance, notepad.exe , not just notepad .

This integration goes deep enough that you can pass information back and forth between Linux and Windows using the normal pipeline mechanisms.

So let's say that you were writing Linux code that needed information from the Windows API, you could always spawn a Windows .exe process which returned the needed information through stdout , and capture that in the Linux app.

This is possible even from the command-line. For instance, in bash :

np=$(powershell.exe -c "(Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\NetworkProvider\HwOrder\).ProviderOrder")
echo $np
# Returns:  P9NP,RDPNP,LanmanWorkstation,webclient

This calls PowerShell using process substitution. PowerShell then executes a Get-ItemProperty for a registry entry. The $np (network provider) variable is set to the results, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM