Python ctypes API call results in Access Violation

  api, ctypes, python, windows

I am trying to list a directory with FindFirstFileW and FindNextFileW in python using ctypes. The FindFirstFileW is successful but FindNextFileW or FindClose results in OSError: exception: access violation writing 0xFFFFFFFFB8093F80

This is the code:

def assert_success(success):
    if not success:
        raise AssertionError(FormatError())

def assert_handle(handle):
    if handle == INVALID_HANDLE_VALUE:
        raise AssertionError(FormatError())
    

def FindFirstFileW(lpFileName):
    wfd = WIN32_FIND_DATAW()
    handle = windll.kernel32.FindFirstFileW(lpFileName, byref(wfd))
    assert_handle(handle)
    return handle, wfd

def FindNextFileW(handle):
    wfd = WIN32_FIND_DATAW()
    success = windll.kernel32.FindNextFileW(handle, byref(wfd))
    assert_success(success)
    return wfd

def FindClose(handle):
    success = windll.kernel32.FindClose(handle)
    assert_success(success)
    return success

handle, wfd = FindFirstFileW('C:Windows*')
print(wfd.cFileName)
wfd = FindNextFileW(handle)
print(wfd.cFileName)
FindClose(handle)

Source: Windows Questions

LEAVE A COMMENT