简体   繁体   中英

How do I call a windows dll function from cygwin python?

I have a Windows python3.7 function which successfully calls the kernel32.dll GetSystemPowerStatus function using ctypes to interrogate the power status to see if my laptop is on AC or battery power. This is a pure python solution.

I want to port this function to cygwin python3.7 . Out of the box, python3 for cygwin 's ctypes does not seem to allow calling a windows dll. I would prefer a pure python solution, but I can use C/C++ if necessary. Does anyone have an example of how to do this?

Edited to add the code (lines 63-67) and error messages:

elif _os.name == 'posix' and _sys.platform == 'cygwin':
    # c:\Windows\System32\kernel32.dll
    kernel32_name = '/proc/cygdrive/c/Windows/System32/kernel32.dll'
    kernel32 = CDLL(kernel32_name)
    _GetSystemPowerStatus = kernel32.GetSystemPowerStatus


$ python3.7 GetSystemPowerStatus.py
Traceback (most recent call last):
  File "GetSystemPowerStatus.py", line 82, in <module>
    result, systemPowerStatus = GetSystemPowerStatus()
  File "GetSystemPowerStatus.py", line 66, in GetSystemPowerStatus
    kernel32 = CDLL(kernel32_name)
  File "/usr/lib/python3.7/ctypes/__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: Invalid argument

python2.7 gives the same error, but at line 366.

Solved. See my own answer below.

As you I wasn't able to get kernel32.dll (although it works with other DLLs like user32 , msvcrt , kernelbase , etc.)

I found a pretty contrived way of doing it... This uses kernelbase.dll (which exports GetModuleHandle ) to get an handle on kernel32.dll , then call CDLL with the handle optional keyword:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import ctypes

def main():
    # the idea is to load kernelbase.dll which will allow us to call GetModuleHandleW() on kernel32.dll
    try:
        kernel_base = ctypes.CDLL("/cygdrive/c/windows/system32/kernelbase.dll")
    except OSError:
        print("Can't load kernelbase.dll...")
        return -1

    gmhw = kernel_base.GetModuleHandleW
    gmhw.argtypes = (ctypes.c_wchar_p, )
    gmhw.restype = ctypes.c_void_p

    # call GetModuleHandleW on kernel32.dll (which is loaded by default in the Python process)
    kernel32_base_addr = gmhw("kernel32.dll")
    print(f"Got kernel32 base address: {kernel32_base_addr:#x}")

    # now call CDLL with optional arguments
    kernel32 = ctypes.CDLL("/cygdrive/c/windows/system32/kernel32.dll", handle=kernel32_base_addr, use_last_error=True)

    # test with GetSystemPowerStatus
    print(f"GetSystemPowerStatus: {kernel32.GetSystemPowerStatus}")

    return 0

if __name__ == "__main__":
    sys.exit(main())

After finding that I could load user32.dll easily, I did some more investigation with the source and pdb and ldd . What follows is my solution.

elif _os.name == 'posix' and _sys.platform == 'cygwin':
    RTLD_LOCAL = 0  # from /usr/include/dlfcn.h
    RTLD_LAZY = 1
    RTLD_NOW = 2
    RTLD_GLOBAL = 4
    RTLD_NODELETE = 8
    RTLD_NOLOAD = 16
    RTLD_DEEPBIND = 32
    kernel32_name = '/proc/cygdrive/c/Windows/System32/kernel32.dll'
    kernel32 = CDLL(kernel32_name, mode=RTLD_LAZY | RTLD_NOLOAD)
    _GetSystemPowerStatus = kernel32.GetSystemPowerStatus

The common code to call the function is:

_GetSystemPowerStatus.restype = c_bool
_GetSystemPowerStatus.argtypes = [c_void_p,]

_systemPowerStatus = _SystemPowerStatus()  # not shown, see ctypes module doc

result = _GetSystemPowerStatus(byref(_systemPowerStatus))

return result, SystemPowerStatus(_systemPowerStatus)

This works fine with Python 2.7, 3.6 and 3.6 on

$ uname -a
CYGWIN_NT-10.0 host 3.0.1(0.338/5/3) 2019-02-20 10:19 x86_64 Cygwin

Thanks to all for their help.

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