0

我正在为某人编写一个 Python3 脚本,该脚本通过 ctypes 使用 advapi dll 及其 LogonUserW 函数。

运行代码时

__init__函数中

dll_location = find_library("advapi32");

if (dll_location == None):
    raise FileNotFoundError

adv_dll = WinDLL(dll_location);

#gets the pointer to the function
logonUser = adv_dll.LogonUserW;
self.logonUser = logonUser

在 login(username, domain, password) 函数中

#Sets the parameters to call the DLL
loginType = DWORD(2)
loginProvider = DWORD(0)
handle = PHANDLE()
user = LPCSTR(username.encode());
pw = LPCSTR(password.encode());
dom = LPCSTR(domain.encode());

rescode = self.logonUser(user, dom, pw, loginType, loginProvider, handle);

它提出了OSError: exception: access violation writing 0x0000000000000000

知道什么可能导致错误以及如何解决吗?

PS:是的,我知道我没有遵循 PEP 8 的变量名,我通常是一名 java 程序员。

4

1 回答 1

1

根据[Python]: types - A foreign function library for Python,您应该为您正在调用的函数设置argtypesand restype(这是一种方式)([MS.Docs]: LogonUserW function)。

下面是一个调用它的最小示例。但是,如果您需要调用多个此类函数,您还可以考虑[GitHub]: Python for Windows (pywin32) Extensions,它是WINAPI的Python包装器。

代码.py

import sys
import ctypes
from ctypes import wintypes


def main():
    advapi32_dll = ctypes.WinDLL("advapi32.dll")
    logon_user_func = advapi32_dll.LogonUserW
    logon_user_func.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.PHANDLE]
    logon_user_func.restype = wintypes.BOOL

    user = "dummy_user"
    domain = "dummy_domain"
    pwd = "dummy_pwd"
    logon_type = 2
    provider = 0
    handle = wintypes.HANDLE()
    ret = logon_user_func(user, domain, pwd, logon_type, provider, ctypes.byref(handle))
    print("{:s} returned {:}".format(logon_user_func.__name__, "TRUE" if ret else "FALSE"))


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main()

备注

  • 除了argtypes/ restypes
    • Python3中,字符串默认是的,所以不需要encode()
    • HANDLE是通过byref

输出

(py35x64_test) e:\Work\Dev\StackOverflow\q051251086>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32

LogonUserW returned FALSE
于 2018-07-09T19:44:50.920 回答