PYTHON - Ctypes:OSError:异常:访问冲突写入0xFFFFFFFFFA1C001B

时间:2018-02-14 13:36:35

标签: python ctypes dllimport memory-mapped-files

这是使用内存映射将值写入内存的代码。当我尝试运行代码时,我收到错误     “文件”MMF.py“,第26行,in     memcpy(pBuf,szMsg,len(szMsg))     OSError:异常:访问冲突写入0xFFFFFFFFFA1C001B“

import msvcrt, mmap
import ctypes
from ctypes import *

FILE_MAP_ALL_ACCESS = 0x04
INVALID_HANDLE_VALUE = 0xFFFFFFFF
SHMEMSIZE = 256
PAGE_READWRITE = 0x04
szName = ctypes.c_wchar_p("MyFileMappingObject")
szMsg = "Message from Python(ctypes) process"

hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE,None, PAGE_READWRITE, 0, SHMEMSIZE, szName)
print("Handle:",hMapObject)
if (hMapObject == 0):
    print("Could not open file mapping object")
    raise WinError()

pBuf = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS,0, 0, SHMEMSIZE)
print("Buffer Starting Addr:",pBuf)
if (pBuf == 0):
    print("Could not map view of file")
    raise WinError()
else:
    print(len(szMsg))
    memcpy = cdll.msvcrt.memcpy
    memcpy(pBuf, szMsg, len(szMsg))

shmem = mmap.mmap(0, 256, "MyFileMappingObject_ctypes", mmap.ACCESS_WRITE)
shmem.write("Message Python process")

msvcrt.getch()

windll.kernel32.UnmapViewOfFile(pBuf)
windll.kernel32.CloseHandle(hMapObject)
shmem.close()

1 个答案:

答案 0 :(得分:2)

在此之前,这里(几乎)所需要的一切:[Python 3]: ctypes - A foreign function library for Python。未解释ctypes.wintypes,但您可以通过在 Python 控制台中运行dir(ctypes.wintypes)来查看其导出。请注意,所有这些类型都是简单的 ctypes 类型,我只是为了约定/一致性/可读性而使用它们。

您的更新代码( code.py ):

#!/usr/bin/env python3

import sys
from ctypes import windll, cdll,\
    c_wchar, c_size_t, c_ulonglong, c_wchar_p, c_void_p,\
    sizeof,\
    WinError
from ctypes.wintypes import BOOL, DWORD, HANDLE, LPCWSTR, LPCVOID, LPVOID
import mmap


if __name__ == "__main__":
    print("Python {:s} on {:s}".format(sys.version, sys.platform))
    FILE_MAP_ALL_ACCESS = 0x000F001F
    INVALID_HANDLE_VALUE = -1
    SHMEMSIZE = 0x100
    PAGE_READWRITE = 0x04


    kernel32_dll = windll.kernel32
    msvcrt_dll = cdll.msvcrt


    create_file_mapping_func = kernel32_dll.CreateFileMappingW
    create_file_mapping_func.argtypes = (HANDLE, LPVOID, DWORD, DWORD, DWORD, LPCWSTR)
    create_file_mapping_func.restype = HANDLE

    map_view_of_file_func = kernel32_dll.MapViewOfFile
    map_view_of_file_func.argtypes = (HANDLE, DWORD, DWORD, DWORD, c_ulonglong)
    map_view_of_file_func.restype = LPVOID

    memcpy_func = msvcrt_dll.memcpy
    memcpy_func.argtypes = (c_void_p, c_void_p, c_size_t)
    memcpy_func.restype = LPVOID

    rtl_copy_memory_func = kernel32_dll.RtlCopyMemory
    rtl_copy_memory_func.argtypes = (LPVOID, LPCVOID, c_ulonglong)

    unmap_view_of_file_func = kernel32_dll.UnmapViewOfFile
    unmap_view_of_file_func.argtypes = (LPCVOID,)
    unmap_view_of_file_func.restype = BOOL

    close_handle_func = kernel32_dll.CloseHandle
    close_handle_func.argtypes = (HANDLE,)
    close_handle_func.restype = BOOL

    get_last_error_func = kernel32_dll.GetLastError
    getch_func = msvcrt_dll._getch


    file_mapping_name_ptr = c_wchar_p("MyFileMappingObject")
    msg = "Message from Python(ctypes) process"
    msg_ptr = c_wchar_p(msg)

    mapping_handle = create_file_mapping_func(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, SHMEMSIZE, file_mapping_name_ptr)

    print("Mapping object handle: 0x{:016X}".format(mapping_handle))
    if not mapping_handle:
        print("Could not open file mapping object: {:d}".format(get_last_error_func()))
        raise WinError()

    mapped_view_ptr = map_view_of_file_func(mapping_handle, FILE_MAP_ALL_ACCESS, 0, 0, SHMEMSIZE)

    print("Mapped view addr: 0x{:016X}".format(mapped_view_ptr))
    if not mapped_view_ptr:
        print("Could not map view of file: {:d}".format(get_last_error_func()))
        close_handle_func(mapping_handle)
        raise WinError()

    byte_len = len(msg) * sizeof(c_wchar)
    print("Message length: {:d} chars ({:d} bytes)".format(len(msg), byte_len))

    memcpy_func(mapped_view_ptr, msg_ptr, byte_len)
    rtl_copy_memory_func(mapped_view_ptr, msg_ptr, byte_len)

    unmap_view_of_file_func(mapped_view_ptr)
    close_handle_func(mapping_handle)


    shmem = mmap.mmap(0, 256, "MyFileMappingObject_ctypes", mmap.ACCESS_WRITE)
    shmem.write(b"Message Python process")
    shmem.close()


    print("Hit a key to exit...")
    getch_func()

备注

  • 为这些功能添加了 argtypes restype 。详细信息可以在" 指定所需的参数类型(函数原型)"和" 返回类型"部分,当然还有MSDN用于函数声明
  • memcpy nd 参数是 Python 字符串,相同的char *地址(更不用说 Python 3 ,字符串 wchar_t memcpy 预计,这可能会产生未定义的行为
  • FILE_MAP_ALL_ACCESS 的值为 0x000F001F (打印出来自 VStudio 2015 的值), 0x04 对应于 FILE_MAP_READ
  • INVALID_HANDLE_VALUE 的旧值转换为 HANDLE 时出错,将其更改为-1(如 handleapi.h )< / LI>
  • 您正在使用 c_wchar_p 调用 CreateFileMappingA 。这将设置一个名称,该名称仅包含映射对象提供的字符串中的1 st 字符,因为每个 wcha_t 包含2个字节: 0x00 加上相应的 char 值 - &#39; A &#39;将表示为 0x00 0x41 (通常这是 true - 尤其是 0x00 部分,但在我们的情况下,它是 - )所以 lpName 参数中的 nd char (由于 little-endianness )将 0x00 NULL
  • 无需导入 msvcrt 模块,仅用于 _getch vcruntime140.dll ucrtbase.dll < / em>的)
  • 根据上面的页面:

      

    通过cdll.msvcrt访问标准C库将使用该库的过时版本,该版本可能与Python使用的版本不兼容。

    所以,我还添加了[Docs.MS]: RtlCopyMemory function来替换memcpy(你可以注释掉它的行,我把它留在那里只是为了证明它有效),如示例所示([MS.Docs]: Creating Named Shared Memory )你从中获取代码并尝试转换它([ minwinbase.h:36 ]:#define CopyMemory RtlCopyMemory

  • 将命名约定更改为 Python 兼容([Python]: PEP 8 -- Style Guide for Python Code
  • 其他(非关键)更改(输出格式,移动代码行以获得更好的结构,等等......)

<强>输出

(py35x64_test) E:\Work\Dev\StackOverflow\q048788549>"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
Mapping object handle: 0x000000000000012C
Mapped view addr: 0x00000206E3BD0000
Message length: 35 chars (70 bytes)
Hit a key to exit...