简体   繁体   English

从 WSL 运行 Windows API 函数

[英]Running Windows API functions from WSL

I was wondering if there is a way to run Windows API functions from WSL1 or WSL2.我想知道是否有办法从 WSL1 或 WSL2 运行 Windows API 函数。 It sounds unlikely in WSL2 since it uses Hypervisor and not aware to the Windows environment, but maybe using WSL1?在 WSL2 中听起来不太可能,因为它使用 Hypervisor 并且不知道 Windows 环境,但也许使用 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 API“混合和匹配”到 Linux ELF 二进制文件中,那么不能直接使用,但请参阅下面的解决方法(这可能是您正在寻找的方法)。

Windows executables using the Windows API will run just fine under both WSL1 and WSL2.使用 Windows API 的 Windows可执行文件在 WSL1 和 WSL2 下都可以正常运行。 To quote from this SU answer , this works because:引用this SU answer ,这是有效的,因为:

The Windows executable (PE binary) is added as a binfmt_misc entry in WSL2. Windows 可执行文件(PE 二进制文件)作为 binfmt_misc 条目添加到 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.简单来说,binfmt_misc 是一个 Linux 内核特性,它允许识别任意可执行文件格式并将其传递给某些程序。

Note that you do need to specify the .exe for a Windows binary to run.请注意,您确实需要为要运行的 Windows 二进制文件指定.exe For instance, notepad.exe , not just notepad .例如, notepad.exe ,而不仅仅是notepad

This integration goes deep enough that you can pass information back and forth between Linux and Windows using the normal pipeline mechanisms.这种集成足够深入,您可以使用正常的管道机制在 Linux 和 Windows 之间来回传递信息。

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.因此,假设您正在编写需要来自 Windows API 的信息的 Linux 代码,您始终可以生成一个 Windows .exe进程,该进程通过stdout返回所需的信息,并在 Linux 应用程序中捕获该信息。

This is possible even from the command-line.这甚至可以从命令行进行。 For instance, in bash :例如,在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。 PowerShell then executes a Get-ItemProperty for a registry entry. PowerShell 然后为注册表项执行 Get-ItemProperty。 The $np (network provider) variable is set to the results, of course.当然, $np (网络提供商)变量设置为结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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