the windows API does not work with python3 but works with python 2

0

I have a python script that I'm trying to convert from python 2.7 to python 3.7. The script includes windows API to read the system registry. In python 2.7 it works correctly. In python 3.7 it does not return the correct result.

I try to run the script python 3 in another PC with python 3. I run the script only in powershell like administrator. https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexa this is the documentation of RegOpenKeyExA() function. In python 2.7 I installed "VCForPython27.msi" from: https://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi which for windows 3.7 I don't find a updated version.

from ctypes import c_uint, c_char_p, byref, windll
subkey = 'JD'    

def RegOpenKeyEx(subkey):
        hkey = c_uint(0) ## Initialize to an int
        windll.advapi32.RegOpenKeyExA(0x80000002, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\' + subkey, 0, 0xF003F , byref(hkey))
        print(hkey.value)
        return hkey.value

In python 2.7 the output is: 656 and the windll.advapi32.RegOpenKeyExA function returns 0 as a return value.

In python 3.7 the output is: 0 and the windll.advapi32.RegOpenKeyExA function returns 2 as a return value

python-3.x
windows
asked on Stack Overflow Aug 12, 2019 by Matteo Dal Grande • edited Aug 12, 2019 by Matteo Dal Grande

1 Answer

0

I solved with replace the 6th row with:

windll.advapi32.RegOpenKeyExA(0x80000002, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\'.encode('ascii') + subkey.encode('ascii'), 0, 0x19 , byref(hkey))

In Python 2.7, strings are byte-strings by default. In Python 3.x, they are unicode by default. I explicitly making string a byte string using .encode('ascii').

answered on Stack Overflow Aug 12, 2019 by Matteo Dal Grande

User contributions licensed under CC BY-SA 3.0