Eryk Sun <eryk...@gmail.com> added the comment:

> ctypes.windll.kernel32.VirtuAlloc function return by default 
> a ctypes.c_long

In Windows, ctypes.c_int is an alias for ctypes.c_long, which is a signed 
32-bit integer. This is the default conversion type for the integer parameters 
of an FFI (foreign function interface) call, as well as the result. It's up to 
the author of a library wrapper to define the correct function prototypes, 
pointer types, and aggregate struct/union types. Some common Windows types are 
defined/aliased in the ctypes.wintypes module, but none of the API is 
prototyped.

> ctypes.windll.kernel32.VirtuAlloc

I suggest avoiding the global ctypes.windll loader. IMO, it's not a great idea 
to use a global library loader since it caches WinDLL instances, which cache 
function pointer instances. This make it possible for unrelated projects to 
interfere with each other and the main script by defining incompatible function 
prototypes -- particularly for common Windows API functions. It also doesn't 
allow passing use_last_error=True to enable the safe capturing of the thread's 
last error value as ctypes.get_last_error().

I recommend creating individual CDLL / WinDLL instances. For example:

    import ctypes

    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

    kernel32.VirtualAlloc.restype = ctypes.c_void_p
    kernel32.VirtualAlloc.argtypes = (
        ctypes.c_void_p, # lpAddress
        ctypes.c_size_t, # dwSize
        ctypes.c_ulong,  # flAllocationType
        ctypes.c_ulong)  # flProtect

If the call fails, you can raise an OSError as follows:

    base_addr = kernel32.VirtualAlloc(None, size, alloc_type, protect)
    if base_addr is None:
        raise ctypes.WinError(ctypes.get_last_error())

----------
components: +ctypes
nosy: +eryksun
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44051>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to