git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

why same ctypes code runs on win7, but not on win10?


On 6/19/20, oyster <lepto.python at gmail.com> wrote:
> The attachment is a very simple code that uses the DLL from
> https://github.com/ying32/govcl to create a GUI application. The code
> runs on my python 3.6.10 64 bits with win7 64 bits, but failed on my
> python 3.6.10 64 bits and python 3.7.5 with win10 64 bits, by saying
> following message. What is the problem? Thanks.
> ```
> vcl.Application_Initialize(Application)
> OSError: exception: access violation reading 0xFFFFFFFF9BCEE490
> ```

The default return type is a 32-bit signed integer, and apparently
Application_Instance returns a memory address (i.e. a pointer). You
can't rely on a 64-bit process loading DLLs and allocating memory only
in the lower 32-bit address space. The following should fix the
problem:

    import ctypes

    # In Python 3.8+, ctypes no longer searches PATH or the
    # current working directory when loading DLLs.
    liblcl_path = 'path/to/liblcl.dll'
    vcl = ctypes.CDLL(liblcl_path)

    # Use a c_void_p subclass, which, unlike c_void_p itself,
    # will not be automatically converted to a Python integer.
    class vclapp_p(ctypes.c_void_p):
        """VCL Application Instance"""

    # Override the default c_int result type.
    vcl.Application_Instance.restype = vclapp_p

    def main():
        app = vcl.Application_Instance()
        vcl.Application_Initialize(app)
        form = vcl.Application_CreateForm(app, False)
        vcl.Application_Run(app)